How to Close Position by selected pip ranges

Created at 12 Oct 2017, 08:04
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!
DA

davideng5555

Joined 06.03.2017

How to Close Position by selected pip ranges
12 Oct 2017, 08:04


Hi, How to Close Position by selected pip ranges?

Only to close winning positions with pips range from '5 to 20'

Thank you

 


@davideng5555
Replies

PanagiotisCharalampous
12 Oct 2017, 14:05

Hi davideng5555,

Try the following condition

                if (position.Pips > 5 && position.Pips < 20)
                {
                    ClosePosition(position);
                }

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 14:30

RE:

Hi Panagiotis.

Good afternoon, thank you for the script.

Which line to insert this script at?

Thank you

--------------

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

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MULTIMARKETORDER : Robot
    {
        [Parameter("Lot Size", DefaultValue = 0.01)]
        public double lot { get; set; }
        [Parameter("Positions nr.", DefaultValue = 100)]
        public int nr { get; set; }
        [Parameter("Buy ?")]
        public bool buy { get; set; }
        [Parameter("Sell ?")]
        public bool sell { get; set; }
        protected override void OnStart()
        {
            long volume = Symbol.QuantityToVolume(lot);
            if (buy)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Buy, Symbol, volume);
            }
            if (sell)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Sell, Symbol, volume);
            }
        }


    }
}

 

 


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 14:39

Hi

It depends where you want to make the check. If you want to make it on each candlestick change, try the following

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

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MULTIMARKETORDER : Robot
    {
        [Parameter("Lot Size", DefaultValue = 0.01)]
        public double lot { get; set; }
        [Parameter("Positions nr.", DefaultValue = 100)]
        public int nr { get; set; }
        [Parameter("Buy ?")]
        public bool buy { get; set; }
        [Parameter("Sell ?")]
        public bool sell { get; set; }
        protected override void OnStart()
        {
            long volume = Symbol.QuantityToVolume(lot);
            if (buy)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Buy, Symbol, volume);
            }
            if (sell)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Sell, Symbol, volume);
            }
        }

        protected override void OnBar()
        {
            foreach (var position in Positions)
            {
                if (position.Pips > 5 && position.Pips < 20)
                {
                    ClosePosition(position);
                }
            }
        }
    }
}

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 14:50

RE:

Hi Panagiotis.

It will be great if the numbers can be selected manually from a box.

-------------

 if (position.Pips > 5 && position.Pips < 20)

                {

                    ClosePosition(position);

Thank you very much.

David 

 


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 14:55

Hi davideng5555,

Here it is :)

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

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class MULTIMARKETORDER : Robot
    {
        [Parameter("Lot Size", DefaultValue = 0.01)]
        public double lot { get; set; }
        [Parameter("Positions nr.", DefaultValue = 100)]
        public int nr { get; set; }
        [Parameter("Buy ?")]
        public bool buy { get; set; }
        [Parameter("Sell ?")]
        public bool sell { get; set; }
        [Parameter("Min TP")]
        public double MinTP { get; set; }
        [Parameter("Max TP")]
        public double MaxTP { get; set; }
        protected override void OnStart()
        {
            long volume = Symbol.QuantityToVolume(lot);
            if (buy)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Buy, Symbol, volume);
            }
            if (sell)
            {
                for (int i = 0; i < nr; i++)
                    ExecuteMarketOrder(TradeType.Sell, Symbol, volume);
            }
        }

        protected override void OnBar()
        {
            foreach (var position in Positions)
            {
                if (position.Pips > MinTP && position.Pips < MaxTP)
                {
                    ClosePosition(position);
                }
            }
        }
    }
}

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 14:58

RE:

Hi Panagiotis,

Thank you very much, I will run the bot and try it.

Best Regards

David

 


@davideng5555

davideng5555
12 Oct 2017, 15:46

RE:

Hi Panagiotis,

What to do when trying to edit a robot, and there is only this message.

'Source code is not available.'

Thank you very much

David.

 


@davideng5555

davideng5555
12 Oct 2017, 16:37

RE:

Hi Panagiotis,

How to make your script into a stand alone robot.

-------------------------------------------------------------

                if (position.Pips > MinTP && position.Pips < MaxTP)

                {

                    ClosePosition(position);

                }

Thank you very much, I tried without success.

Best Regards

David

 

 

 


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 16:41

RE: RE:

davideng5555 said:

Hi Panagiotis,

What to do when trying to edit a robot, and there is only this message.

'Source code is not available.'

Thank you very much

David.

 

This means that the cBot's creator did not provide the source code therefore you cannot edit the cBot


@PanagiotisCharalampous

PanagiotisCharalampous
12 Oct 2017, 16:43

RE: RE:

davideng5555 said:

Hi Panagiotis,

How to make your script into a stand alone robot.

-------------------------------------------------------------

                if (position.Pips > MinTP && position.Pips < MaxTP)

                {

                    ClosePosition(position);

                }

Thank you very much, I tried without success.

Best Regards

David

 

 

 

Hi David,

You cannot make the specific script a stand alone cBot. It needs to be a part of a Robot class. Maybe you could elaborate on what you want to achieve?

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 16:53

RE: RE: RE:

Hi Panagiotis,

How to built a code to close all the winning postions, within the selected pip range.

Thank you very much,

Best Regards

David


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 16:59

Hi David,

Use the code below

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;
 
namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class SamplecBot: Robot
    {       
        [Parameter("Min TP")]
        public double MinTP { get; set; }
        [Parameter("Max TP")]
        public double MaxTP { get; set; }   
 
        protected override void OnTick()
        {
            foreach (var position in Positions)
            {
                if (position.Pips > MinTP && position.Pips < MaxTP)
                {
                    ClosePosition(position);
                }
            }
        }
    }
}

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 17:07

RE:

Hi Panagiotis,

Thank you very much, tested with great results.

Is there a way to speed up the execution?

Best Regards

David


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 17:09

Hi David,

Why do you believe the execution is slow?

Best Regards,

Panagiotis


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 17:17

RE:

 

Hi Panagiotis,

During execution, it is a bit lagging while searching for the selected value,

Is it the way I arrange the postions at the 'position box'?

Best Regards

David


@davideng5555

PanagiotisCharalampous
12 Oct 2017, 17:51

No that should not be the reason. How many positions do you have open and how many are getting closed in a tick?


@PanagiotisCharalampous

davideng5555
12 Oct 2017, 18:05

RE:

Just a few positions were opened during the test, ranges all within 25 pips.

Used many old 'close position bots' in the past and they all are different.

But the CLOSE ALL can close many hundred positions in a wink.

Maybe I was a bit too sensitive.

Thank you very much.

 


@davideng5555

animegalaxi
07 Nov 2017, 09:53

Hi all,

I\ve a question that its almost related to this.

I'm using a break even, that after a number of pips, moves the stopp loss to entryprice plus few pips, and its workin ok.

But i woulk like, if possible, like in this case, when the stopploss is moving, close 2/3 of my volum, i'm trading 0.3 lots.

I'm trying many thigs that i found on this forum, but it'n not working... i spent so many hours try to figure it out, but nothing.

I just start with c#, to make my bot i use the online service of Fxpro, quant.fxpro.co.uk, from there i made the code for the break even.

 

My question is, there's some "universal" code, that can works, that allows to close 0.2 lots of 0.3 after the break even moves the stopp loss?

Usualy, i'm still trying, but i set after 6pips the stoploss is moving to entry price.

 

Thanks really a lot.

 

Nicola


@animegalaxi

PanagiotisCharalampous
07 Nov 2017, 11:10

Hi animegalaxi,

Thanks for posting in our forum! See below an example of how you can close approximately 2/3 of a position. Note that the closing volume should always adhere to the Symbol's volume step requirements, therefore the exact 2/3 is not always achievable.

                var steps = Positions[0].Volume / Symbol.VolumeStep;
                var stepsToClose = (int)(steps * 2 / 3);
                ClosePosition(Positions[0], Symbol.VolumeStep * stepsToClose);

Best Regards,

Panagiotis


@PanagiotisCharalampous

animegalaxi
07 Nov 2017, 11:33

//+------------------------------------------------------------------+
//+                           Code generated using FxPro Quant 2.1.4 |
//+------------------------------------------------------------------+

using System;
using System.Threading;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;


namespace cAlgo.Robots
{
   [Robot(TimeZone = TimeZones.UTC)]
   public class Prototype : Robot
   {


      //Global declaration

DateTime LastTradeExecution = new DateTime(0);

      protected override void OnStart()
      {

      }

      protected override void OnTick() 
      {
         if (Trade.IsExecuting) return;

         //Local declaration
         TriState _Break_Even = new TriState();
         TriState _Buy = new TriState();

         //Step 1
         _Break_Even = Break_Even(0, 200);

         //Step 2
            

      }

bool NoOrders(string symbolCode, double[] magicIndecies){if (symbolCode == "")symbolCode = Symbol.Code;string[] labels = new string[magicIndecies.Length];for (int i = 0; i < magicIndecies.Length; i++){labels[i] = "FxProQuant_" + magicIndecies[i].ToString("F0");}foreach (Position pos in Positions){if (pos.SymbolCode != symbolCode)continue;if (labels.Length == 0)return false;foreach (var label in labels){if (pos.Label == label)return false;}}foreach (PendingOrder po in PendingOrders){if (po.SymbolCode != symbolCode)continue;if (labels.Length == 0)return false;foreach (var label in labels){if (po.Label == label)return false;}}return true;}

TriState _OpenPosition(double magicIndex, bool noOrders, string symbolCode, TradeType tradeType, double lots, double slippage, double? stopLoss, double? takeProfit, string comment){Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);if (noOrders && Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)return new TriState();if (stopLoss < 1)stopLoss = null;if (takeProfit < 1)takeProfit=null;if(symbol.Digits==5||symbol.Digits == 3){if (stopLoss != null)stopLoss /= 10;if (takeProfit != null)takeProfit /= 10;slippage /= 10;}int volume = Convert.ToInt32(lots * 100000);if (!ExecuteMarketOrder(tradeType, symbol, volume, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, slippage, comment).IsSuccessful){Thread.Sleep(400);return false;}return true;}

TriState _SendPending(double magicIndex, bool noOrders, string symbolCode, PendingOrderType poType, TradeType tradeType, double lots, int priceAction, double priceValue, double? stopLoss, double? takeProfit,DateTime? expiration, string comment){Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);if (noOrders && PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol) != null)return new TriState();if (stopLoss < 1)stopLoss = null;if (takeProfit < 1)takeProfit = null;if (symbol.Digits == 5 || symbol.Digits == 3){if (stopLoss != null)stopLoss /= 10;if (takeProfit != null)takeProfit /= 10;}int volume = Convert.ToInt32(lots * 100000);double targetPrice;switch (priceAction){case 0:targetPrice = priceValue;break;case 1:targetPrice = symbol.Bid - priceValue * symbol.TickSize;break;case 2:targetPrice = symbol.Bid + priceValue * symbol.TickSize;break;case 3:targetPrice = symbol.Ask - priceValue * symbol.TickSize;break;case 4:targetPrice = symbol.Ask + priceValue * symbol.TickSize;break;default:targetPrice = priceValue;break;}if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))expiration = null;if (poType == PendingOrderType.Limit){if (!PlaceLimitOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful){Thread.Sleep(400);return false;}return true;}else if (poType == PendingOrderType.Stop){if (!PlaceStopOrder(tradeType, symbol, volume, targetPrice, "FxProQuant_" + magicIndex.ToString("F0"), stopLoss, takeProfit, expiration, comment).IsSuccessful){Thread.Sleep(400);return false;}return true;}return new TriState();}

TriState _ModifyPosition(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue){Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (pos == null)return new TriState();double? sl, tp;if (slValue == 0)sl = null;else{switch (slAction){case 0:sl = pos.StopLoss;break;case 1:if (pos.TradeType == TradeType.Buy)sl = pos.EntryPrice - slValue * symbol.TickSize;else sl = pos.EntryPrice + slValue * symbol.TickSize;break;case 2:sl = slValue;break;default:sl = pos.StopLoss;break;}}if (tpValue == 0)tp = null;else{switch (tpAction){case 0:tp = pos.TakeProfit;break;case 1:if (pos.TradeType == TradeType.Buy)tp = pos.EntryPrice + tpValue * symbol.TickSize;else tp = pos.EntryPrice - tpValue * symbol.TickSize;break;case 2:tp = tpValue;break;default:tp = pos.TakeProfit;break;}}if (!ModifyPosition(pos, sl, tp).IsSuccessful){Thread.Sleep(400);return false;}return true;}

TriState _ModifyPending(double magicIndex, string symbolCode, int slAction, double slValue, int tpAction, double tpValue, int priceAction, double priceValue, int expirationAction, DateTime? expiration){Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (po == null)return new TriState();double targetPrice;double? sl, tp;if (slValue == 0)sl = null;else{switch (slAction){case 0:sl = po.StopLoss;break;case 1:if (po.TradeType == TradeType.Buy)sl = po.TargetPrice - slValue * symbol.TickSize;else sl = po.TargetPrice + slValue * symbol.TickSize;break;case 2:sl = slValue;break;default:sl = po.StopLoss;break;}}if (tpValue == 0)tp = null;else{switch (tpAction){case 0:tp = po.TakeProfit;break;case 1:if (po.TradeType == TradeType.Buy)tp = po.TargetPrice + tpValue * symbol.TickSize;else tp = po.TargetPrice - tpValue * symbol.TickSize;break;case 2:tp = tpValue;break;default:tp = po.TakeProfit;break;}}switch (priceAction){case 0:targetPrice = po.TargetPrice;break;case 1:targetPrice = priceValue;break;case 2:targetPrice = po.TargetPrice + priceValue * symbol.TickSize;break;case 3:targetPrice = po.TargetPrice - priceValue * symbol.TickSize;break;case 4:targetPrice = symbol.Bid - priceValue * symbol.TickSize;break;case 5:targetPrice = symbol.Bid + priceValue * symbol.TickSize;break;case 6:targetPrice = symbol.Ask - priceValue * symbol.TickSize;break;case 7:targetPrice = symbol.Ask + priceValue * symbol.TickSize;break;default:targetPrice = po.TargetPrice;break;}if (expiration.HasValue && (expiration.Value.Ticks == 0 || expiration.Value == DateTime.Parse("1970.01.01 00:00:00")))expiration = null;if (expirationAction == 0)expiration = po.ExpirationTime;if (!ModifyPendingOrder(po, targetPrice, sl, tp, expiration).IsSuccessful){Thread.Sleep(400);return false;}return true;}

TriState _ClosePosition(double magicIndex, string symbolCode, double lots){Symbol symbol = (Symbol.Code == symbolCode) ? Symbol : MarketData.GetSymbol(symbolCode);var pos = Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (pos == null)return new TriState();TradeResult result;if (lots == 0){result = ClosePosition(pos);}else{int volume = Convert.ToInt32(lots * 100000);result = ClosePosition(pos, volume);}if (!result.IsSuccessful){Thread.Sleep(400);return false;}return true;}

TriState _DeletePending(double magicIndex, string symbolCode){Symbol symbol = (Symbol.Code == symbolCode)?Symbol:MarketData.GetSymbol(symbolCode);var po=PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (po == null)return new TriState();if (!CancelPendingOrder(po).IsSuccessful){Thread.Sleep(400);return false;}return true;}

bool _OrderStatus(double magicIndex, string symbolCode, int test){Symbol symbol=(Symbol.Code==symbolCode)?Symbol:MarketData.GetSymbol(symbolCode);var pos=Positions.Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (pos != null){if (test == 0)return true;if (test == 1)return true;if (test == 3)return pos.TradeType == TradeType.Buy;if (test == 4)return pos.TradeType == TradeType.Sell;}var po = PendingOrders.__Find("FxProQuant_" + magicIndex.ToString("F0"), symbol);if (po != null){if (test == 0)return true;if (test == 2)return true;if (test == 3)return po.TradeType == TradeType.Buy;if (test == 4)return po.TradeType == TradeType.Sell;if (test == 5)return po.OrderType == PendingOrderType.Limit;if (test == 6)return po.OrderType == PendingOrderType.Stop;}return false;}

int TimeframeToInt(TimeFrame tf){if(tf == TimeFrame.Minute) return 1;else if (tf == TimeFrame.Minute2) return 2;else if (tf == TimeFrame.Minute3) return 3;else if (tf == TimeFrame.Minute4) return 4;else if (tf == TimeFrame.Minute5) return 5;else if (tf == TimeFrame.Minute10) return 10;else if (tf == TimeFrame.Minute15) return 15;else if (tf == TimeFrame.Minute30) return 30;else if (tf == TimeFrame.Hour) return 60;else if (tf == TimeFrame.Hour4) return 240;else if (tf == TimeFrame.Daily) return 1440;else if (tf == TimeFrame.Weekly) return 10080;else if (tf == TimeFrame.Monthly) return 43200;return 1;}


DateTime __currentBarTime = DateTime.MinValue;
bool __isNewBar(bool triggerAtStart)
{
    DateTime newTime = MarketSeries.OpenTime.LastValue;
    if (__currentBarTime != newTime)
    {
        if (!triggerAtStart && __currentBarTime == DateTime.MinValue)
        {
            __currentBarTime = newTime;
            return false;
        }
        __currentBarTime = newTime;
        return true;
    }
    return false;
}


TriState Buy(double magicIndex, double Lots, int StopLossMethod, double stopLossValue, int TakeProfitMethod, double takeProfitValue, double Slippage, double MaxOpenTrades, double MaxFrequencyMins, string TradeComment)
{
	double? stopLossPips, takeProfitPips;
	int numberOfOpenTrades = 0;
	var res = new TriState();

	foreach (Position pos in Positions.FindAll("FxProQuant_" + magicIndex.ToString("F0"), Symbol))
	{
		numberOfOpenTrades++;
	}

	if (MaxOpenTrades > 0 && numberOfOpenTrades >= MaxOpenTrades)
		return res;

	if (MaxFrequencyMins > 0)
	{
		if (((TimeSpan)(Server.Time - LastTradeExecution)).TotalMinutes < MaxFrequencyMins)
			return res;

		foreach (Position pos in Positions.FindAll("FxProQuant_" + magicIndex.ToString("F0"), Symbol))
		{
			if (((TimeSpan)(Server.Time - pos.EntryTime)).TotalMinutes < MaxFrequencyMins)
				return res;
		}
	}

	int pipAdjustment = Convert.ToInt32(Symbol.PipSize / Symbol.TickSize);

	if (stopLossValue > 0)
	{
		if (StopLossMethod == 0)
			stopLossPips = stopLossValue / pipAdjustment;
		else if (StopLossMethod == 1)
			stopLossPips = stopLossValue;
		else
			stopLossPips = (Symbol.Ask - stopLossValue) / Symbol.PipSize;
	}
	else
		stopLossPips = null;

	if (takeProfitValue > 0)
	{
		if (TakeProfitMethod == 0)
			takeProfitPips = takeProfitValue / pipAdjustment;
		else if (TakeProfitMethod == 1)
			takeProfitPips = takeProfitValue;
		else
			takeProfitPips = (takeProfitValue - Symbol.Ask) / Symbol.PipSize;
	}
	else
		takeProfitPips = null;

	Slippage /= pipAdjustment;
	long volume = Symbol.NormalizeVolume(Lots * 100000, RoundingMode.ToNearest);

	if (!ExecuteMarketOrder(TradeType.Buy, Symbol, volume, "FxProQuant_" + magicIndex.ToString("F0"), stopLossPips, takeProfitPips, Slippage, TradeComment).IsSuccessful)
	{
		Thread.Sleep(400);
		return false;
	}
	LastTradeExecution = Server.Time;
	return true;
}


TriState Break_Even(double magicIndex, double BreakEvenPoints)
{
	double pnlPoints = 0;
	var res = new TriState();

	foreach (Position pos in Positions.FindAll("FxProQuant_" + magicIndex.ToString("F0"), Symbol))
	{
		if (pos.TradeType == TradeType.Buy)
		{
			pnlPoints = (Symbol.Bid - pos.EntryPrice) / Symbol.TickSize;
			if (pnlPoints < BreakEvenPoints)
				continue;

			if (pos.StopLoss != null)
			{
				if (pos.EntryPrice <= pos.StopLoss)
					continue;
			}

			var result = ModifyPosition(pos, pos.EntryPrice, pos.TakeProfit);
			if (result.IsSuccessful && res.IsNonExecution)
				res = true;
			else
			{
				Thread.Sleep(400);
				res = false;
			}
		}
		else
		{
			pnlPoints = (pos.EntryPrice - Symbol.Ask) / Symbol.TickSize;
			if (pnlPoints < BreakEvenPoints)
				continue;

			if (pos.StopLoss != null)
			{
				if (pos.EntryPrice >= pos.StopLoss)
					continue;
			}

			if (pos.StopLoss == null || pos.EntryPrice < pos.StopLoss)
			{
				var result = ModifyPosition(pos, pos.EntryPrice, pos.TakeProfit);
				if (result.IsSuccessful && res.IsNonExecution)
					res = true;
				else
				{
					Thread.Sleep(400);
					res = false;
				}
			}
		}
	}
	return res;
}
   
}
}

public struct TriState{public static readonly TriState NonExecution = new TriState(0);public static readonly TriState False = new TriState(-1);public static readonly TriState True = new TriState(1);sbyte value;TriState(int value){this.value = (sbyte)value;}public bool IsNonExecution{get { return value == 0; }}public static implicit operator TriState(bool x){return x ? True : False;}public static TriState operator ==(TriState x, TriState y){if (x.value == 0 || y.value == 0)return NonExecution;return x.value == y.value ? True : False;}public static TriState operator !=(TriState x, TriState y){if (x.value == 0 || y.value == 0)return NonExecution;return x.value != y.value ? True : False;}public static TriState operator !(TriState x){return new TriState(-x.value);}public static TriState operator &(TriState x, TriState y){return new TriState(x.value < y.value ? x.value : y.value);}public static TriState operator |(TriState x, TriState y){return new TriState(x.value > y.value ? x.value : y.value);}public static bool operator true(TriState x){return x.value > 0;}public static bool operator false(TriState x){return x.value < 0;}public static implicit operator bool(TriState x){return x.value > 0;}public override bool Equals(object obj){if (!(obj is TriState))return false;return value == ((TriState)obj).value;}public override int GetHashCode(){return value;}public override string ToString(){if (value > 0)return "True";if (value < 0)return "False";return "NonExecution";}}

public static class PendingEx{public static PendingOrder __Find(this cAlgo.API.PendingOrders pendingOrders, string label, Symbol symbol){foreach (PendingOrder po in pendingOrders){if (po.SymbolCode == symbol.Code && po.Label == label)return po;}return null;}}

Hi Panagiotis, thanks for you answer.

Sorry if i bother you for another question, up it's let's say the "base" of code with breakeven included to the buy order, the breakeven code is almost at the end of code, i select it in bold and italic.

Where can put you're code?

Really thanks.

Nicola


@animegalaxi

PanagiotisCharalampous
07 Nov 2017, 11:46

Hi Nicola,

From a first sight, you could put it in the end of the foreach loop, so that the position is partially closed just after the modification. However, if you are not experienced in C# programming, I would strongly advise you to collaborate with a professional programmer to make such changes, to avoid the risk of unintended results. There is a lot of code in the cBot and will require proper testing to verify that your change does exactly what you wanted to achieve.

Best Regards,

Panagiotis


@PanagiotisCharalampous

animegalaxi
07 Nov 2017, 11:54

Hi,

Ok i'll try, in case yes, i'll conctact an expert as you suggest.

Really thanks a lot!

Nicola


@animegalaxi

davideng5555
10 Nov 2017, 16:08

RE:

Panagiotis Charalampous said:

Hi animegalaxi,

Thanks for posting in our forum! See below an example of how you can close approximately 2/3 of a position. Note that the closing volume should always adhere to the Symbol's volume step requirements, therefore the exact 2/3 is not always achievable.

                var steps = Positions[0].Volume / Symbol.VolumeStep;
                var stepsToClose = (int)(steps * 2 / 3);
                ClosePosition(Positions[0], Symbol.VolumeStep * stepsToClose);

 

Hi, is it possible to combine this script above with the other one you wrote below?

Thank you very much,

David

---------------------------------------------------------

using System;

using System.Linq;

using cAlgo.API;

using cAlgo.API.Indicators;

using cAlgo.API.Internals;

using cAlgo.Indicators;

  

namespace cAlgo

{

    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]

    public class SamplecBot: Robot

    {      

        [Parameter("Min TP")]

        public double MinTP { get; set; }

        [Parameter("Max TP")]

        public double MaxTP { get; set; }  

  

        protected override void OnTick()

        {

            foreach (var position in Positions)

            {

                if (position.Pips > MinTP && position.Pips < MaxTP)

                {

                    ClosePosition(position);

                }

            }

        }

    }

}

 


@davideng5555

davideng5555
13 Nov 2017, 16:07

RE:

Panagiotis Charalampous said:

Hi animegalaxi,

Thanks for posting in our forum! See below an example of how you can close approximately 2/3 of a position. Note that the closing volume should always adhere to the Symbol's volume step requirements, therefore the exact 2/3 is not always achievable.

                var steps = Positions[0].Volume / Symbol.VolumeStep;
                var stepsToClose = (int)(steps * 2 / 3);
                ClosePosition(Positions[0], Symbol.VolumeStep * stepsToClose);

Best Regards,

Panagiotis

 

Hi Panagiotis,

Can you please post the full script of "Close approximately 2/3 of a position".

Is it possible to combine with the Close Position you wrote?

Thank you very much,

David

 


@davideng5555

PanagiotisCharalampous
20 Nov 2017, 11:06

Hi davideng5555,

There is no full script. It is just the three lines above that show how to calculate the 2/3 of a position and use it in the ClosePosition function.

Is it possible to combine with the Close Position you wrote?

Can you please point me to the code you refer to and what you would actually like to achieve?

Best Regards,

Panagiotis 


@PanagiotisCharalampous