Topics
05 Dec 2014, 00:00
 2524
 1
Replies

admin
18 Apr 2013, 12:16

Refer to this msdn topic on How to: Use Anonymous Pipes for Local Interprocess Communication  to create a client exe file pipeClient and save the executable in the public documents directory: C:\Users\Public\Documents

using System;
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using cAlgo.API;

namespace cAlgo.Robots
{
    [Robot]
    public class PipeServer : Robot
    {
        private readonly Process _pipeClient = new Process();

        [Parameter("Text", DefaultValue = "Message from Server")]
        public string InputText { get; set; }

        [Parameter(DefaultValue = "pipeClient.exe")]
        public string FileName { get; set; }

        protected override void OnStart()
        {
            using (var pipeServer =
                new AnonymousPipeServerStream(PipeDirection.Out,
                                              HandleInheritability.Inheritable))
            {
                // filename of the client
                string filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments),
                                               FileName);

                _pipeClient.StartInfo.FileName = filename;
                // Pass the client process a handle to the server.
                _pipeClient.StartInfo.Arguments =
                    pipeServer.GetClientHandleAsString();
                _pipeClient.StartInfo.UseShellExecute = false;
                // Start the client
                _pipeClient.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    // Send some text to the client process. 
                    using (var sw = new StreamWriter(pipeServer))
                    {
                        sw.AutoFlush = true;
                        // Send a 'sync message' and wait for client to receive it.
                        sw.WriteLine("SYNC");
                        pipeServer.WaitForPipeDrain();
                        // Send the input text to the client process.
                        Print("Passing text to client: {0} ", InputText);
                        sw.WriteLine(InputText);
                        // Send the currency pair to the client process.
                        sw.WriteLine(Symbol.Code);
                    }
                }
                    // Catch the IOException that is raised if the pipe is broken 
                    // or disconnected. 
                catch (IOException e)
                {
                    Print("Error: {0}", e.Message);
                }
            }

            _pipeClient.WaitForExit();
            _pipeClient.Close();
            Print("Client quit. Server terminating.");
            // Stop the robot
            Stop();
        }
    }
}

 


@admin

admin
15 Apr 2013, 12:07

// -------------------------------------------------------------------------------------------------
//
//    Simple Moving Average Shift
//    This code is a cAlgo API example.
//    
// -------------------------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator(IsOverlay = true)]
    public class SMAShift : Indicator
    {
        [Parameter]
        public DataSeries Source { get; set; }

        [Parameter(DefaultValue = 14)]
        public int Period { get; set; }

        [Parameter(DefaultValue = 5, MinValue = -100, MaxValue = 500)]
        public int Shift { get; set; }

        [Output("Main", Color = Colors.Blue)]
        public IndicatorDataSeries Result { get; set; }

        private SimpleMovingAverage _simpleMovingAverage;
        
        protected override void Initialize()
        {
            _simpleMovingAverage = Indicators.SimpleMovingAverage(Source, Period);
        }

        public override void Calculate(int index)
        {
            if(Shift < 0 && index < Math.Abs(Shift))
                return;

            Result[index + Shift] = _simpleMovingAverage.Result[index];
        }
    }
}

 


@admin

admin
03 Apr 2013, 17:12

You may use this code to create a custom MACD Crossover Indicator.

 

using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{    
    [Indicator("MACD Crossover", ScalePrecision = 5)]
    public class MacdCrossOver : Indicator
    {
        private ExponentialMovingAverage _emaLong;
        private ExponentialMovingAverage _emaShort;
        private ExponentialMovingAverage _emaSignal;

        [Parameter("Long Cycle", DefaultValue = 26)]
        public int LongCycle { get; set; }

        [Parameter("Short Cycle", DefaultValue = 12)]
        public int ShortCycle { get; set; }

        [Parameter("Signal Periods", DefaultValue = 9)]
        public int SignalPeriods { get; set; }

        [Output("Histogram", Color = Colors.Turquoise, PlotType = PlotType.Histogram)]
        public IndicatorDataSeries Histogram { get; set; }

        [Output("MACD", Color = Colors.Blue)]
        public IndicatorDataSeries MACD { get; set; }

        [Output("Signal", Color = Colors.Red, LineStyle = LineStyle.Lines)]
        public IndicatorDataSeries Signal { get; set; }

        protected override void Initialize()
        {
            _emaLong = Indicators.ExponentialMovingAverage(MarketSeries.Close, LongCycle);
            _emaShort = Indicators.ExponentialMovingAverage(MarketSeries.Close, ShortCycle);
            _emaSignal = Indicators.ExponentialMovingAverage(MACD, SignalPeriods);
        }

        public override void Calculate(int index)
        {
            MACD[index] = _emaShort.Result[index] - _emaLong.Result[index];
            Signal[index] = _emaSignal.Result[index];
            Histogram[index] = MACD[index] - Signal[index];
        }
    }
}



 


@admin

admin
02 Apr 2013, 14:25

Use this code to create a custom stochastic oscillator by adjusting the code to your needs.

 

using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Levels(20, 50, 70)]
    [Indicator]
    public class CustomStochasticOscillator : Indicator
    {
        private IndicatorDataSeries _fastK;
        private MovingAverage _slowK;
        private MovingAverage _averageOnSlowK;

        [Parameter("K Periods", DefaultValue = 9, MinValue = 1)]
        public int KPeriods { get; set; }

        [Parameter("K Slowing", DefaultValue = 3, MinValue = 2)]
        public int KSlowing { get; set; }

        [Parameter("D Periods", DefaultValue = 9, MinValue = 0)]
        public int DPeriods { get; set; }

        [Parameter("MA Type", DefaultValue = MovingAverageType.Simple)]
        public MovingAverageType MAType { get; set; }

        [Output("%D", Color = Colors.Red, LineStyle = LineStyle.Lines)]
        public IndicatorDataSeries PercentD { get; set; }

        [Output("%K", Color = Colors.Green)]
        public IndicatorDataSeries PercentK { get; set; }


        protected override void Initialize()
        {
            _fastK = CreateDataSeries();
            _slowK = Indicators.MovingAverage(_fastK, KSlowing, MAType);

            _averageOnSlowK = Indicators.MovingAverage(_slowK.Result, DPeriods, MAType);
        }

        public override void Calculate(int index)
        {
            _fastK[index] = GetFastKValue(index);

            PercentK[index] = _slowK.Result[index];
            PercentD[index] = _averageOnSlowK.Result[index];
        }

        private double GetFastKValue(int index)
        {
            var lowestLow = MarketSeries.Low.Minimum(KPeriods);
            var hightestHigh = MarketSeries.High.Maximum(KPeriods);
            var currentClose = MarketSeries.Close[index];

            return 100 * (currentClose - lowestLow) / (hightestHigh - lowestLow);
        }
    }
}




@admin

admin
02 Apr 2013, 11:52

Use this code to create a custom RSI in order to make modifications such as adjusting the Levels of the RSI indicator. 

For example you may change the code of [Levels(25, 50, 75)] to the values of your choice.

using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Indicators
{
    [Indicator]
    [Levels(25, 50, 75)]
    public class RSI:Indicator
    {
        [Parameter]
        public DataSeries Source { get; set; }

        [Parameter(DefaultValue = 14, MinValue = 1)]
        public int Periods { get; set; }

        [Output("Main", Color = Colors.Green)]
        public IndicatorDataSeries Result { get; set; }

        private IndicatorDataSeries _profit;
        private IndicatorDataSeries _loss;

        private ExponentialMovingAverage _emaProfit;
        private ExponentialMovingAverage _emaLoss;

        protected override void Initialize()
        {
            _profit = CreateDataSeries();
            _loss = CreateDataSeries();
            
            var emaPeriods = 2 * Periods - 1;

            _emaProfit = Indicators.ExponentialMovingAverage(_profit, emaPeriods);
            _emaLoss = Indicators.ExponentialMovingAverage(_loss, emaPeriods);
        }

        public override void Calculate(int index)
        {
            var lastPrice = Source[index];
            var previousPrice = Source[index - 1];

            if (lastPrice > previousPrice)
            {
                _profit[index] = lastPrice - previousPrice;
                _loss[index] = 0.0;
            }
            else if (lastPrice < previousPrice)
            {
                _profit[index] = 0.0;
                _loss[index] = previousPrice - lastPrice;
            }
            else
            {
                _profit[index] = 0.0;
                _loss[index] = 0.0;
            }

            var relativeStrength = _emaProfit.Result[index] / _emaLoss.Result[index];

            Result[index] = 100 - (100 / (1 + relativeStrength));
            
        }
    }
}


@admin

admin
21 Mar 2013, 12:53

// -------------------------------------------------------------------------------------------------
//
//    This robot 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 Limit Trailing Stop" Robot places a Buy or Sell Limit order according to user input.  
//    When the order is filled it implements trailing stop loss.
//
// -------------------------------------------------------------------------------------------------

using System;
using cAlgo.API;

namespace cAlgo.Robots
{
    [Robot("Sample Limit Trailing Stop")]
    public class SampleLimitTrailingStop : Robot
    {
        [Parameter("Position Label", DefaultValue = "Limit Trailing Stop")]
        public string MyLabel { get; set; }

        [Parameter("Buy", DefaultValue = true)]
        public bool TradeTypeBuy { get; set; }
        
        [Parameter(DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Target Price (pips)", DefaultValue = 10, MinValue = 1)]
        public int TargetPricePips { get; set; }

        [Parameter()]
        public double Price { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 50, MinValue = 1)]
        public int StopLossPips { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 50, MinValue = 1)]
        public int TakeProfitPips { get; set; }

        [Parameter("Trigger (pips)", DefaultValue = 20)]
        public int Trigger { get; set; }

        [Parameter("Trailing Stop (pips)", DefaultValue = 10)]
        public int TrailingStop { get; set; }


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

            double targetPrice = ValidatePrice();
            var tradeType = TradeTypeBuy ? TradeType.Buy : TradeType.Sell;
            PlaceLimitOrder(tradeType, Symbol, Volume, targetPrice, MyLabel, StopLossPips, TakeProfitPips);
            
        }

        private void PositionsOnClosed(PositionClosedEventArgs args)
        {
            if (args.Position.Label == MyLabel)
                Stop();
        }

        private double ValidatePrice()
        {
            double targetPrice;

            if (TradeTypeBuy)
            {
                var buyPrice = Symbol.Ask - TargetPricePips*Symbol.PipSize;
                targetPrice = Price==0.0? buyPrice: Math.Min(Price, buyPrice);
            }
            else
            {
                var sellPrice = Symbol.Bid + TargetPricePips * Symbol.PipSize;
                targetPrice = Price == 0.0 ? sellPrice : Math.Max(Price, sellPrice);
            }
            
            return targetPrice;

        }


        protected override void OnTick()
        {
            var position = Positions.Find(MyLabel);
            if (position == null) return;

            double profit = TradeTypeBuy
                                  ? Symbol.Bid - position.EntryPrice
                                  : position.EntryPrice - Symbol.Ask;
            if (profit >= Trigger*Symbol.PipSize)
                AdjustStopLoss();
        }

        private void AdjustStopLoss()
        {
            double newStopLossPrice = TradeTypeBuy
                              ? Symbol.Bid - TrailingStop * Symbol.PipSize
                              : Symbol.Ask + TrailingStop * Symbol.PipSize;
            
            Position position = Positions.Find(MyLabel);
            bool modify = TradeTypeBuy
                                     ? newStopLossPrice > position.StopLoss
                                     : newStopLossPrice < position.StopLoss;
            if (modify)
            {
                ModifyPosition(position, newStopLossPrice, position.TakeProfit);
            }
        }

    }
}

 


@admin

admin
01 Mar 2013, 14:25

Let us know if the code below serves the purpose:

public override void Calculate(int index)
{
    if (!IsRealTime) return;

    for (int i = index - 10; i <= index; i++)
    {
        Result[i] = _simpleMovingAverage1.Result[index];
        Result2[i] = _simpleMovingAverage2.Result[index];
        Result3[i] = _simpleMovingAverage3.Result[index];
        Result4[i] = _simpleMovingAverage4.Result[index];
        Result5[i] = _simpleMovingAverage5.Result[index];
        Result6[i] = _simpleMovingAverage6.Result[index];
        Result7[i] = _simpleMovingAverage7.Result[index];
    }
    for(int i = 0; i < index - 10; i++)
    {
        Result[i] = double.NaN;
        Result2[i] = double.NaN;
        Result3[i] = double.NaN;
        Result4[i] = double.NaN;
        Result5[i] = double.NaN;
        Result6[i] = double.NaN;
        Result7[i] = double.NaN;
    }
    int xPos = index + 6;
    double yPos = _simpleMovingAverage1.Result[index];
    var text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj1", text, xPos, yPos, VerticalAlignment.Center, HorizontalAlignment.Left,Colors.Lime);

    yPos = _simpleMovingAverage2.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj2", text, xPos, yPos, VerticalAlignment.Bottom, HorizontalAlignment.Left,Colors.Yellow);

    yPos = _simpleMovingAverage3.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj3", text, xPos, yPos, VerticalAlignment.Center, HorizontalAlignment.Left,Colors.White);

    yPos = _simpleMovingAverage4.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj4", text, xPos, yPos, VerticalAlignment.Top, HorizontalAlignment.Left, Colors.Aqua);

    yPos = _simpleMovingAverage5.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj5", text, xPos, yPos, VerticalAlignment.Top, HorizontalAlignment.Left, Colors.Blue);

    yPos = _simpleMovingAverage6.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj6", text, xPos, yPos, VerticalAlignment.Top, HorizontalAlignment.Left,Colors.Orange);

    yPos = _simpleMovingAverage7.Result[index];
    text = String.Format("{0}", Math.Round(yPos, Symbol.Digits));
    ChartObjects.DrawText("obj7", text, xPos, yPos, VerticalAlignment.Top, HorizontalAlignment.Left, Colors.Red);
}



Multi-time frames will be supported in the future.


@admin

admin
01 Mar 2013, 11:47

The code executes only within a specific time interval of the day. The input parameters for the start and stop time are in hours. For instance, if the Start Hour is 10 and the Stop Hour is 12, the robot will only execute when the server time is between 10am and 12am.

using System;
using cAlgo.API;
using cAlgo.API.Indicators;

namespace cAlgo.Robots
{
    [Robot]
    public class SampleTradingTime2 : Robot
    {
        private DateTime _startTime;
        private DateTime _stopTime;
        private BollingerBands _bollingerBands;

        [Parameter("Start Hour", DefaultValue = 10.0)]
        public double StartTime { get; set; }

        [Parameter("Stop Hour", DefaultValue = 12.0)]
        public double StopTime { get; set; }


        protected override void OnStart()
        {
            // Start Time is the same day at 22:00:00 Server Time
            _startTime = Server.Time.Date.AddHours(StartTime);

            // Stop Time is the next day at 06:00:00
            _stopTime = Server.Time.Date.AddHours(StopTime);

            Print("Start Time {0},", _startTime);
            Print("Stop Time {0},", _stopTime);

            _bollingerBands = Indicators.BollingerBands(MarketSeries.Close, 20, 2, MovingAverageType.Simple);
        }

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

            var currentHours = Server.Time.TimeOfDay.TotalHours;
            bool tradeTime = StartTime < StopTime
                ? currentHours > StartTime && currentHours < StopTime
                : currentHours < StopTime || currentHours > StartTime;

            if (!tradeTime)
                return;

            if (Positions.Count != 0) return;

            var top = _bollingerBands.Top.LastValue;
            var bottom = _bollingerBands.Bottom.LastValue;

            if (Symbol.Ask > top)                
                ExecuteMarketOrder(TradeType.Buy, Symbol, 10000);
            else if (Symbol.Bid < bottom)
                ExecuteMarketOrder(TradeType.Sell, Symbol, 10000);
        }
    }
}

 


@admin

admin
20 Feb 2013, 09:31

Hello,

You may send us the code so that we can investigate it at engage@ctrader.com.


@admin

admin
18 Feb 2013, 16:45 ( Updated at: 15 Jan 2024, 14:50 )

Please refer to this example robot: [/forum/calgo-reference-samples/499].

Unfortunately for the time being you cannot create an indicator to calculate this because there is no access to the Account Interface from indicators.


@admin

admin
18 Feb 2013, 16:38

    Calculation of Maximum allowed trading volume if Margin = Volume/Leverage.

    Based on base currency equal to account currency (Margin = Volume/Leverage).

    For example: Account Deposit in EUR

    and currency pairs of all positions are EURxxx(e.g. EURUSD)

    For other combinations the equation of Margin must be adjusted.

 

 

 

// -------------------------------------------------------------------------------
//
//    This is a Template used as a guideline to build your own Robot. 
//    Please use the “Feedback” tab to provide us with your suggestions about cAlgo’s API.
//
//    Calculation of Maximum allowed trading volume if Margin = Volume/Leverage.
//    Based on base currency equal to account currency (Margin = Volume/Leverage).
//    For example: Account Deposit in EUR
//    and currency pairs of all positions are EURxxx(e.g. EURUSD)
//    For other combinations the equation of Margin must be adjusted.
//
// -------------------------------------------------------------------------------

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

namespace cAlgo.Robots
{
    [Robot]
    public class MaxTradeVolume : Robot
    {
        private int _maxVolume;
    	
        [Parameter(DefaultValue = 100)]
        public int Leverage { get; set; }


        protected override void OnStart()
        {
            bool notBaseCurrency = Account.Positions.Any(position => !position.SymbolCode.StartsWith(Account.Currency));
            if (notBaseCurrency)
            {
                Print("Position base currency must be deposit currency");
                Stop();
            }
        }


        private int CalculateMaxVolume()
        {
            return (int)Math.Truncate(Math.Round(Account.Equity * Leverage * 100 / 101) / 10000) * 10000;
        }


        protected override void OnTick()
        {
            _maxVolume = CalculateMaxVolume();
            var text = String.Format("{0}",_maxVolume);
            ChartObjects.DrawText("objVolume", text, StaticPosition.TopLeft, Colors.White);
        }


    }
}




@admin

admin
18 Feb 2013, 12:07

Please look at the  SampleSellTrailing Robot that is included in cAlgo as well as /forum/calgo-reference-samples/55.


@admin

admin
18 Feb 2013, 11:54

Please refer to the MathWorks website for help on using Matlab with C#.


@admin

admin
18 Feb 2013, 11:53

The Calculate method is called on each tick.  If this is not what you need please rephrase. What exactly are you trying to accomplish?


@admin

admin
18 Feb 2013, 11:50

We are looking into this. Thank you for reporting it.


@admin

admin
18 Feb 2013, 10:21

Which namespace are your refering to? System.Net is accessible right now.


@admin

admin
18 Feb 2013, 10:07

You don't need a reference for that example. It is using a system namespace:  InteropServices

 

using System.Runtime.InteropServices;

 


@admin

admin
18 Feb 2013, 10:00

You don't need a reference. Just this namespace System.Runtime.InteropServices;


@admin

admin
18 Feb 2013, 09:54

You need to replace Result with atr in the FibonacciBands  indicator or replace atr with Result in the averageTrueRange indicator (this requires a build of the averageTrueRange indicator as well)

First option(FibonacciBands):

 public override void Calculate(int index)
        {
            double ema = _exponentialMovingAverage.Result[index];
            double atr = _averageTrueRange.atr[index];

 


Second option (averageTrueRange ):

[Output("AverageTrueRange", Color = Colors.Orange)]
public IndicatorDataSeries Result { get; set; }


 


@admin