Open opposite trade

Created at 29 Apr 2016, 21:36
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!
SL

slootwege

Joined 03.04.2016

Open opposite trade
29 Apr 2016, 21:36


I just want code I can use so that when a position closes, the robot will open a position in the opposite direction. There doesn't seem to be anything simple to do it in the API; something like a TradeType.Opposite.

A little context:

My idea is to have a robot that starts by opening a random position. If the position moves above $5 in profit it starts a trailing stop, and when the position closes it opens a new position in the same direction. If the opened position moves below $3 in losses, I want the robot to close the position and open a new position in the opposite direction. I've got most of it figured out except for the opening a position in the opposite direction bit, which I can't wrap my head around. I have very little background in coding.


@slootwege
Replies

croucrou
30 Apr 2016, 14:26

Use "PositionClosedEventArgs" with conditions:

"if" position's gross profit <= 3$ check both conditions:

"if" position's trade type = buy, execute sell,

"if" position's trade type = sell, execute buy.


@croucrou

... Deleted by UFO ...

slootwege
30 Apr 2016, 18:32

Thank you, Lucian, that is an incredibly helpful starting point.


@slootwege

ahs41ene09
06 Nov 2016, 10:36

Hi all,

I was interrested in this forum because I need an opposite trading position.

I am currently working on the sample martingale available in the C-Algo.

Below I have pasted the coding for this sample. In bold, "a new order of the same type (Buy / Sell) is created. I want it to be of the opposite type. Any input on this please?

Thanks!

// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API sample.
//
//    This cBot is intended to be used as a sample and does not guarantee any particular outcome or
//    profit of any kind. Use it at your own risk
//
//    The "Sample Martingale cBot" creates a random Sell or Buy order. If the Stop loss is hit, a new 
//    order of the same type (Buy / Sell) is created
with double the Initial Volume amount. The cBot will 
//    continue to double the volume amount for  all orders created until one of them hits the take Profit. 
//    After a Take Profit is hit, a new random Buy or Sell order is created with the Initial Volume amount.
//
// -------------------------------------------------------------------------------------------------

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 SampleMartingalecBot : Robot
    {
        [Parameter("Initial Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)]
        public double InitialQuantity { get; set; }

        [Parameter("Stop Loss", DefaultValue = 40)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit", DefaultValue = 40)]
        public int TakeProfit { get; set; }

        private Random random = new Random();

        protected override void OnStart()
        {
            Positions.Closed += OnPositionsClosed;

            ExecuteOrder(InitialQuantity, GetRandomTradeType());
        }

        private void ExecuteOrder(double quantity, TradeType tradeType)
        {
            var volumeInUnits = Symbol.QuantityToVolume(quantity);
            var result = ExecuteMarketOrder(tradeType, Symbol, volumeInUnits, "Martingale", StopLoss, TakeProfit);

            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }

        private void OnPositionsClosed(PositionClosedEventArgs args)
        {
            Print("Closed");
            var position = args.Position;

            if (position.Label != "Martingale" || position.SymbolCode != Symbol.Code)
                return;

            if (position.GrossProfit > 0)
            {
                ExecuteOrder(InitialQuantity, GetRandomTradeType());
            }
            else
            {
                ExecuteOrder(position.Quantity * 2, position.TradeType);
            }
        }

        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}


@ahs41ene09

... Deleted by UFO ...

ahs41ene09
07 Nov 2016, 08:08

Thanks a lot Lucian, it is very kind of you!


@ahs41ene09

collinganesh
07 Nov 2016, 11:55

RE:

lucian said:

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 SlootWegte : Robot
    {
        [Parameter("Profit $", DefaultValue = 5.0)]
        public double _profit { get; set; }
        [Parameter("Loss $", DefaultValue = -3.0)]
        public double _loss { get; set; }
        [Parameter("Initial Volume", DefaultValue = 10000, MinValue = 0)]
        public int _volume { get; set; }
        private Random random = new Random();

        protected override void OnStart()
        {
            ExecuteOrder(_volume, GetRandomTradeType());
            Positions.Closed += Positions_Closed;
        }

        protected override void OnTick()
        {
            foreach (var trade in Positions)
            {

                if ((trade.Label.StartsWith("SlootWege")) && ((trade.GrossProfit >= _profit) || (trade.GrossProfit <= _loss)))
                {
                    ClosePosition(trade);
                }
            }
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
        private void Positions_Closed(PositionClosedEventArgs args)
        {
            if (args.Position.GrossProfit <= _loss)
            {
                if (args.Position.TradeType == TradeType.Buy)
                {
                    ExecuteOrder(_volume, TradeType.Sell);
                }
                else
                {
                    ExecuteOrder(_volume, TradeType.Buy);
                }
            }
            if (args.Position.GrossProfit >= _profit)
            {
                if (args.Position.TradeType == TradeType.Buy)
                {
                    ExecuteOrder(_volume, TradeType.Buy);
                }
                else
                {
                    ExecuteOrder(_volume, TradeType.Sell);
                }
            }
        }
        private void ExecuteOrder(long volume, TradeType tradeType)
        {
            var result = ExecuteMarketOrder(tradeType, Symbol, volume, "SlootWege", null, null);

            if (result.Error == ErrorCode.NoMoney)
                Stop();
        }
        private TradeType GetRandomTradeType()
        {
            return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell;
        }
    }
}

Hi  Lucian,

                Is it posible for you to code the bot to open buystop orders when buy order stop loss is triggered, instead of reversing the order and same

                for the opposite. 

 

              Thanks

 


@collinganesh

... Deleted by UFO ...