Topics
Replies
tradermatrix
12 Jan 2018, 13:00
thank you
I will test this solution (because it is associated with the label)
I made this code that works (but can unfortunately interfere with other robots)
protected override void OnTick() { Play(); } private void Play() { var volumeInUnits = Symbol.QuantityToVolume(Quantity); var totalOrders = PendingOrders.Count; if (totalOrders >= 1) return; { var buyOrderTargetPrice = Symbol.Ask + PipStepB * Symbol.PipSize; DateTime exp = MarketSeries.OpenTime.LastValue.AddMinutes(MINUTES); PlaceStopOrder(TradeType.Buy, Symbol, volumeInUnits, buyOrderTargetPrice, RobotID, SL, TP, exp); foreach (var pendingOrder in PendingOrders) { Print("Order placed with label {0}, id {1}", pendingOrder.Label, pendingOrder.Id); } } } } }
cordially
@tradermatrix
tradermatrix
07 Jan 2018, 15:51
I found this solution
could someone help me restart automatically (send stop order) when expiration time has deleted stop order
or any other solution would be welcome
cordially
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Reflection; using System.Threading; using System.Diagnostics; using Microsoft.Win32; using cAlgo.API.Requests; using System.Text; namespace cAlgo { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)] public class HigGFrequency : Robot { [Parameter("HigHFreQuencY Label n°", DefaultValue = "1")] public string RobotID { get; set; } [Parameter("Pip Step", DefaultValue = 10, MinValue = 1)] public int PipStepB { get; set; } [Parameter("First Quantity(Lots)", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double Quantity { get; set; } [Parameter("Cancel Stop Order(MINUTES)", DefaultValue = 30)] public int MINUTES { get; set; } [Parameter(DefaultValue = 160)] public int SL { get; set; } [Parameter(DefaultValue = 40)] public int TP { get; set; } ////////////////////////////////////////////////////////////////////////////////////// private bool _ordersCreated; protected override void OnTick() { Play(); } private void Play() { var volumeInUnits = Symbol.QuantityToVolume(Quantity); if (!_ordersCreated) { var buyOrderTargetPrice = Symbol.Ask + PipStepB * Symbol.PipSize; DateTime exp = MarketSeries.OpenTime.LastValue.AddMinutes(MINUTES); _ordersCreated = true; PlaceStopOrder(TradeType.Buy, Symbol, volumeInUnits, buyOrderTargetPrice, RobotID, SL, TP, exp); foreach (var pendingOrder in PendingOrders) { Print("Order placed with label {0}, id {1}", pendingOrder.Label, pendingOrder.Id); } } } } }
@tradermatrix
tradermatrix
31 Oct 2017, 15:11
HI
look at this one it is more efficient and the trailingstop works
using System; using System.Linq; using System.Text; using cAlgo.API; namespace cAlgo.Robots { [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class NewsScalp : Robot { [Parameter("News Day (1-5)", DefaultValue = 1, MinValue = 1, MaxValue = 5)] public int NewsDay { get; set; } [Parameter("News Hour", DefaultValue = 14, MinValue = 0, MaxValue = 23)] public int NewsHour { get; set; } [Parameter("News Minute", DefaultValue = 30, MinValue = 0, MaxValue = 59)] public int NewsMinute { get; set; } [Parameter("Seconds Before", DefaultValue = 10, MinValue = 1)] public int SecondsBefore { get; set; } [Parameter("Seconds Timeout", DefaultValue = 10, MinValue = 1)] public int SecondsTimeout { get; set; } [Parameter("One Cancels Other")] public bool Oco { get; set; } [Parameter("ShowTimeLeftNews", DefaultValue = true)] public bool ShowTimeLeftToNews { get; set; } [Parameter("ShowTimeLeftPlaceOrders", DefaultValue = true)] public bool ShowTimeLeftToPlaceOrders { get; set; } [Parameter("Volume", DefaultValue = 10000, MinValue = 1)] public int Volume { get; set; } [Parameter("Pips away", DefaultValue = 3)] public int PipsAway { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public int TakeProfit { get; set; } [Parameter("Stop Loss", DefaultValue = 20)] public int StopLoss { get; set; } [Parameter("trigger ", DefaultValue = 0)] public int Trigger { get; set; } [Parameter("Trailing", DefaultValue = 10)] public int Trailing { get; set; } private bool _ordersCreated; private DateTime _triggerTimeInServerTimeZone; private const string Label = "News Robot"; protected override void OnStart() { Positions.Opened += OnPositionOpened; Timer.Start(1); var triggerTimeInLocalTimeZone = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, NewsHour, NewsMinute, 0); if (triggerTimeInLocalTimeZone < DateTime.Now) triggerTimeInLocalTimeZone = triggerTimeInLocalTimeZone.AddDays(1); _triggerTimeInServerTimeZone = TimeZoneInfo.ConvertTime(triggerTimeInLocalTimeZone, TimeZoneInfo.Local, TimeZone); } protected override void OnTick() { TRAILING(); } private void TRAILING() { Position[] positions = Positions.FindAll(Label, Symbol); foreach (Position position in positions) { if (position.TradeType == TradeType.Sell) { double distance = position.EntryPrice - Symbol.Ask; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Ask + Trailing * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice < position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } else { double distance = Symbol.Bid - position.EntryPrice; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Bid - Trailing * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice > position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } } } protected override void OnTimer() { if ((int)Server.Time.DayOfWeek == NewsDay && !_ordersCreated) { var remainingTime = _triggerTimeInServerTimeZone - Server.Time; DrawRemainingTime(remainingTime); if (!_ordersCreated) { var sellOrderTargetPrice = Symbol.Bid - PipsAway * Symbol.PipSize; ChartObjects.DrawHorizontalLine("sell target", sellOrderTargetPrice, Colors.Red, 1, LineStyle.DotsVeryRare); var buyOrderTargetPrice = Symbol.Ask + PipsAway * Symbol.PipSize; ChartObjects.DrawHorizontalLine("buy target", buyOrderTargetPrice, Colors.Blue, 1, LineStyle.DotsVeryRare); if (Server.Time <= _triggerTimeInServerTimeZone && (_triggerTimeInServerTimeZone - Server.Time).TotalSeconds <= SecondsBefore) { _ordersCreated = true; var expirationTime = _triggerTimeInServerTimeZone.AddSeconds(SecondsTimeout); PlaceStopOrder(TradeType.Sell, Symbol, Volume, sellOrderTargetPrice, Label, StopLoss, TakeProfit, expirationTime); PlaceStopOrder(TradeType.Buy, Symbol, Volume, buyOrderTargetPrice, Label, StopLoss, TakeProfit, expirationTime); ChartObjects.RemoveObject("sell target"); ChartObjects.RemoveObject("buy target"); } } if (_ordersCreated && !PendingOrders.Any(o => o.Label == Label)) { Print("Orders expired"); return; } } } private void DrawRemainingTime(TimeSpan remainingTimeToNews) { if (ShowTimeLeftToNews) { if (remainingTimeToNews > TimeSpan.Zero) { ChartObjects.DrawText("countdown1", "Time left to news: " + FormatTime(remainingTimeToNews), StaticPosition.TopLeft); } else { ChartObjects.RemoveObject("countdown1"); } } if (ShowTimeLeftToPlaceOrders) { var remainingTimeToOrders = remainingTimeToNews - TimeSpan.FromSeconds(SecondsBefore); if (remainingTimeToOrders > TimeSpan.Zero) { ChartObjects.DrawText("countdown2", "Time left to place orders: " + FormatTime(remainingTimeToOrders), StaticPosition.TopRight); } else { ChartObjects.RemoveObject("countdown2"); } } } private static StringBuilder FormatTime(TimeSpan remainingTime) { var remainingTimeStr = new StringBuilder(); if (remainingTime.TotalHours >= 1) remainingTimeStr.Append((int)remainingTime.TotalHours + "h "); if (remainingTime.TotalMinutes >= 1) remainingTimeStr.Append(remainingTime.Minutes + "m "); if (remainingTime.TotalSeconds > 0) remainingTimeStr.Append(remainingTime.Seconds + "s"); return remainingTimeStr; } private void OnPositionOpened(PositionOpenedEventArgs args) { var position = args.Position; if (position.Label == Label && position.SymbolCode == Symbol.Code) { if (Oco) { foreach (var order in PendingOrders) { if (order.Label == Label && order.SymbolCode == Symbol.Code) { CancelPendingOrderAsync(order); } } } return; } } } }
@tradermatrix
tradermatrix
30 Oct 2017, 21:36
Hello
now it should work
using System; using cAlgo.API; namespace cAlgo.Robots { [Robot(AccessRights = AccessRights.None)] public class TradingNewsRobot : Robot { private PendingOrder _buyOrder; private bool _ordersCreated; private PendingOrder _sellOrder; private Position position; [Parameter("News Day (1-5)", DefaultValue = 1, MinValue = 1, MaxValue = 5)] public int NewsDay { get; set; } [Parameter("News Hour", DefaultValue = 14, MinValue = 0, MaxValue = 23)] public int NewsHour { get; set; } [Parameter("News Minute", DefaultValue = 30, MinValue = 0, MaxValue = 59)] public int NewsMinute { get; set; } [Parameter("Seconds Before", DefaultValue = 5, MinValue = 1)] public int SecondsBefore { get; set; } [Parameter("Seconds Timeout", DefaultValue = 10, MinValue = 1)] public int SecondsTimeout { get; set; } [Parameter("One Cancels Other", DefaultValue = 1, MinValue = 0, MaxValue = 1)] public int Oco { get; set; } [Parameter("Pips away", DefaultValue = 10)] public int PipsAway { get; set; } [Parameter("Volume", DefaultValue = 10000, MinValue = 1000)] public int Volume { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public int TakeProfit { get; set; } [Parameter("Stop Loss", DefaultValue = 10)] public int StopLoss { get; set; } [Parameter("Trigger (pips) if > 0", DefaultValue = 0)] public int Trigger { get; set; } [Parameter("Trailing Stop (pips) if > 0 ", DefaultValue = 0)] public int TrailingStop { get; set; } protected override void OnStart() { MarketData.GetMarketDepth(Symbol).Updated += MarketDepth_Updated; } protected override void OnTick() { if (position == null) return; TRAILING(); } private void TRAILING() { foreach (var position in Positions) { if (TrailingStop > 0 && Trigger > 0) { if (position.TradeType == TradeType.Sell) { double distance = position.EntryPrice - Symbol.Ask; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Ask + TrailingStop * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice < position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } else { double distance = Symbol.Bid - position.EntryPrice; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Bid - TrailingStop * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice > position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } } } } private void MarketDepth_Updated() { if ((int)Server.Time.DayOfWeek == NewsDay && !_ordersCreated) { var triggerTime = new DateTime(Server.Time.Year, Server.Time.Month, Server.Time.Day, NewsHour, NewsMinute, 0); if (Server.Time <= triggerTime && (triggerTime - Server.Time).TotalSeconds <= SecondsBefore) { _ordersCreated = true; DateTime expirationTime = triggerTime.AddSeconds(SecondsTimeout); double sellOrderTargetPrice = Symbol.Bid - PipsAway * Symbol.PipSize; Trade.CreateSellStopOrder(Symbol, Volume, sellOrderTargetPrice, sellOrderTargetPrice + StopLoss * Symbol.PipSize, sellOrderTargetPrice - TakeProfit * Symbol.PipSize, expirationTime); double buyOrderTargetPrice = Symbol.Ask + PipsAway * Symbol.PipSize; Trade.CreateBuyStopOrder(Symbol, Volume, buyOrderTargetPrice, buyOrderTargetPrice - StopLoss * Symbol.PipSize, buyOrderTargetPrice + TakeProfit * Symbol.PipSize, expirationTime); } } } protected override void OnPendingOrderCreated(PendingOrder newOrder) { if (newOrder.TradeType == TradeType.Buy) _buyOrder = newOrder; else _sellOrder = newOrder; } protected override void OnPositionOpened(Position openedPosition) { position = openedPosition; if (Oco == 1) { Trade.DeletePendingOrder(_buyOrder); Trade.DeletePendingOrder(_sellOrder); _ordersCreated = false; } } protected override void OnPositionClosed(Position closedPosition) { position = null; } } }
@tradermatrix
tradermatrix
17 Sep 2017, 00:10
I work a little with FxPro Quant
I transform a few codes
look at your transformed code ... it closes (if request ... !! at a precise time) provided that the position is positive ...
you can also set the minimum amount ....
otherwise c is the SL or TP that closes the position.
you can use it with several instruments at the same time by changing the label on the dashboard
good trade
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 EMA : Robot { [Parameter("EMA Label n°", DefaultValue = "1")] public string RobotID { get; set; } [Parameter("Lot_Size", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double _Lot_Size { get; set; } [Parameter("Max_Spread", DefaultValue = 2)] public int _Max_Spread { get; set; } [Parameter("EMA2_Period", DefaultValue = 50)] public double _EMA2_Period { get; set; } [Parameter("Signal_Period", DefaultValue = 50)] public double _Signal_Period { get; set; } [Parameter("EMA1_Period", DefaultValue = 20)] public double _EMA1_Period { get; set; } [Parameter("hourly_EMA_fast", DefaultValue = 20)] public double _hourly_EMA_fast { get; set; } [Parameter("hourly_EMA_slow", DefaultValue = 200)] public double _hourly_EMA_slow { get; set; } [Parameter("hourly_EMA_middle", DefaultValue = 50)] public double _hourly_EMA_middle { get; set; } [Parameter("EMA3_Period", DefaultValue = 200)] public double _EMA3_Period { get; set; } [Parameter("Stop_Loss", DefaultValue = 1600)] public double _Stop_Loss { get; set; } [Parameter("Take_Profit", DefaultValue = 800)] public double _Take_Profit { get; set; } [Parameter("Start_hour", DefaultValue = 0)] public double _Start_hour { get; set; } [Parameter("End_hour", DefaultValue = 18)] public double _End_hour { get; set; } [Parameter("use close _End_hour", DefaultValue = true)] public bool useclose_End_hour { get; set; } [Parameter("if use close ...Net Gains >", DefaultValue = 20)] public double NetGains { get; set; } private ExponentialMovingAverage i_Signal; private ExponentialMovingAverage i_EMA3; private ExponentialMovingAverage i_EMA1; private ExponentialMovingAverage i_EMA2; private ExponentialMovingAverage i_Daily_EMA200; private ExponentialMovingAverage i_Daily_EMA50; private ExponentialMovingAverage i_Daily_EMA20; double _Signal; double _EMA2; double _Daily_EMA50; DateTime LastTradeExecution = new DateTime(0); protected override void OnStart() { i_Signal = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_Signal_Period); i_EMA3 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA3_Period); i_EMA1 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA1_Period); i_EMA2 = Indicators.ExponentialMovingAverage(MarketSeries.Close, (int)_EMA2_Period); i_Daily_EMA200 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_slow); i_Daily_EMA50 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_middle); i_Daily_EMA20 = Indicators.ExponentialMovingAverage(MarketData.GetSeries(TimeFrame.Hour).Close, (int)_hourly_EMA_fast); } private void gains_End_hour() { if (useclose_End_hour) { var netProfit = 0.0; foreach (var openedPosition in Positions) { if (openedPosition.Label.StartsWith(RobotID)) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); { TriState _Close_Position = new TriState(); if (!IsTime(_Start_hour, _End_hour, 0, 0)) { if (Account.Equity - Account.Balance > NetGains) { if (openedPosition.Label.StartsWith(RobotID)) { _Close_Position = _ClosePosition(1, Symbol.Code, 0); Print("Closed _End_hour "); } } } } } } } protected override void OnTick() { TriState _Open_Long_Position = new TriState(); //Step 1 _Signal = i_Signal.Result.Last(0); _EMA2 = i_EMA2.Result.Last(0); _Daily_EMA50 = i_Daily_EMA50.Result.Last(0); gains_End_hour(); if (((MarketSeries.High.Last(1) < _Signal) && (MarketSeries.High.Last(0) >= _Signal) && (i_EMA1.Result.Last(0) > _EMA2) && (_EMA2 > i_EMA3.Result.Last(0)) && ((Symbol.Bid - (Symbol.Ask)) <= _Max_Spread) && IsTime(_Start_hour, _End_hour, 0, 0) && (i_Daily_EMA20.Result.Last(0) > _Daily_EMA50) && (_Daily_EMA50 > i_Daily_EMA200.Result.Last(0)))) _Open_Long_Position = _OpenPosition(1, true, Symbol.Code, TradeType.Buy, _Lot_Size, 0, _Stop_Loss, _Take_Profit, ""); } bool NoOrders(string symbolCode, double[] magicIndecies) { if (symbolCode == "") symbolCode = Symbol.Code; string[] labels = new string[magicIndecies.Length]; { } 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(RobotID, 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, RobotID, 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(RobotID, 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, RobotID, stopLoss, takeProfit, expiration, comment).IsSuccessful) { Thread.Sleep(400); return false; } return true; } else if (poType == PendingOrderType.Stop) { if (!PlaceStopOrder(tradeType, symbol, volume, targetPrice, RobotID, 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(RobotID, 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(RobotID, 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(RobotID, 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(RobotID, 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(RobotID, 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(RobotID, 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; } bool IsTime(double startHourParam, double endHourParam, double startMinuteParam, double endMinuteParam) { int startHour = Convert.ToInt32(startHourParam); int endHour = Convert.ToInt32(endHourParam); int startMinute = Convert.ToInt32(startMinuteParam); int endMinute = Convert.ToInt32(endMinuteParam); if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 || startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59) return false; int startTime = startHour * 60 + startMinute; int endTime = endHour * 60 + endMinute; int time = Server.Time.Hour * 60 + Server.Time.Minute; if (startTime < endTime) return (time >= startTime && time <= endTime); else if (startTime > endTime) return (time >= startTime || time <= endTime); else return (time == startTime); } } } 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; } }
@tradermatrix
tradermatrix
16 Sep 2017, 13:07
hi
c is because of this sentence:
you automatically close a _End_hour
this sentence should be deleted
protected override void OnTick() { if (Trade.IsExecuting) return; //Local declaration TriState _Close_Position = new TriState(); TriState _Open_Long_Position = new TriState(); //Step 1 _Signal = i_Signal.Result.Last(0); _EMA2 = i_EMA2.Result.Last(0); _Daily_EMA50 = i_Daily_EMA50.Result.Last(0); //Step 2 if (!IsTime(_Start_hour, _End_hour, 0, 0)) _Close_Position = _ClosePosition(1, Symbol.Code, 0);
look you always close at 20h
SymbolOpening DirectionClosing Time (UTC+2)Entry PriceClosing PriceClosing QuantityDID209784513GBPUSDBuy14.09.17 20:231,340151,34005DID209784545GBPUSDBuy14.09.17 20:231,340131,34009DID209784578GBPUSDBuy14.09.17 20:231,340161,34009DID209784589GBPUSDBuy14.09.17 20:231,340161,34009DID209784599GBPUSDBuy14.09.17 20:231,340161,34011DID209784604GBPUSDBuy14.09.17 20:231,340111,34004DID209784612GBPUSDBuy14.09.17 20:231,34011,34004DID209784693GBPUSDBuy14.09.17 20:231,34011,34009DID209784700GBPUSDBuy14.09.17 20:231,340151,34008DID209784718GBPUSDBuy14.09.17 20:231,340151,34008DID209784727GBPUSDBuy14.09.17 20:231,340151,34008DID209784733GBPUSDBuy14.09.17 20:231,340151,34008DID209784764GBPUSDBuy14.09.17 20:231,340161,34009DID209784781GBPUSDBuy14.09.17 20:231,340111,34006DID209784803GBPUSDBuy14.09.17 20:231,34011,34005DID209784838GBPUSDBuy14.09.17 20:231,340111,34005DID209784848GBPUSDBuy14.09.17 20:231,34011,34006DID209784858GBPUSDBuy14.09.17 20:231,340121,34006DID209784869GBPUSDBuy14.09.17 20:231,340111,34004DID209784885GBPUSDBuy14.09.17 20:231,340111,34005DID209784889GBPUSDBuy14.09.17 20:231,34011,34004
@tradermatrix
tradermatrix
21 Aug 2017, 21:55
Excuse my bad explanation.j could have also posted on Ctrader.
I want to say a command to the market directly on the screen (stop or limit) or with Ctrader (no robot) ... the window that opens allows to choose orders "market order" or "limit" or "stop" and "Stop limit order" .and even to post a comment ....
J would have liked to be able to add the function "label".
Because I use small automatic closing robots at a desired price.
Using for example several currencies or indicator I will be able to separate the profits (according to the label that I will have chosen at the moment of placing an order).
thank you
@tradermatrix
tradermatrix
12 Jul 2017, 00:19
RE:
amantalpur007@gmail.com said:
hi, i want a code that stops doubling the position after 4 loses in a row and start with initial amount which has been set. please help me by telling me the code for martingale cbot to stop doubling after 4 trades. please
Hi
Calculate the max volume based on the number of losses you accept.
example:
6 losses..vol 1000 ... Max volume ... return = 32000
If unfortunately you arrive at the end of the logic the vume returns to the initial volume ...
This is what I have most simple in my drawers ...
Good trades.
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 MartingalReturN : Robot { [Parameter("Initial Volume", DefaultValue = 5000)] public int InitialVolume { get; set; } [Parameter(" Max volume...return ", DefaultValue = 40000)] public int MaxRun { get; set; } [Parameter("Stop Loss", DefaultValue = 42)] public int StopLoss { get; set; } [Parameter("Take Profit", DefaultValue = 45)] public int TakeProfit { get; set; } private Random random = new Random(); protected override void OnStart() { Positions.Closed += OnPositionsClosed; ExecuteOrder(InitialVolume, GetRandomTradeType()); } private void ExecuteOrder(long volume, TradeType tradeType) { var result = ExecuteMarketOrder(tradeType, Symbol, volume, "MR", StopLoss, TakeProfit); if (result.Error == ErrorCode.NoMoney) Stop(); } private void OnPositionsClosed(PositionClosedEventArgs args) { Print("Closed"); var position = args.Position; if (position.Label != "MR" || position.SymbolCode != Symbol.Code) return; if (position.GrossProfit > 0) { ExecuteOrder(InitialVolume, GetRandomTradeType()); } else { ExecuteOrder(getNewVolume((int)position.Volume), position.TradeType); } } private TradeType GetRandomTradeType() { return random.Next(2) == 0 ? TradeType.Buy : TradeType.Sell; } private int getNewVolume(int posVol) { var newVol = posVol * 2; newVol = Math.Min(newVol, MaxRun + 1); if (newVol == MaxRun + 1) newVol = InitialVolume; Print("newVol = {0}", newVol); return newVol; } } }
@tradermatrix
tradermatrix
09 Jun 2017, 17:40
Thank you MiKro for your code
I will study all this and try to adapt it.
cordially
@tradermatrix
tradermatrix
31 May 2017, 12:03
RE:
Thank you croucrou
But my system works well.
I just need a code if it is possible to close all my positions (independently for each label) in a single mouse click on the screen.
But I do not know if that's possible ...
@tradermatrix
tradermatrix
06 May 2017, 12:26
RE:
korakodmy said:
Hello everyone
I want to coding expire date in 1 month
Example , Start ea on date 1 May 2017 ea will expire on 1 Jun 2017
Thank you very much
Hello
I dated April 15, 2017 for example baktesting
Made at your convenience..@+
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 EXEMPLE : Robot { [Parameter("Initial Volume", DefaultValue = 10000, MinValue = 0)] public int InitialVolume { get; set; } [Parameter("Stop Loss", DefaultValue = 20)] public int StopLoss { get; set; } [Parameter("Take Profit", DefaultValue = 20)] public int TakeProfit { get; set; } bool timeprotected = true; // if true ;Expiry YEAR MM DD DateTime expirytime = new DateTime(2017, 4, 15); protected override void OnTick() { if (timeprotected == true && DateTime.Compare(Server.Time.Date, expirytime) >= 1) { //your email Informer("Robot Expired!! Please contact .....@...."); Stop(); } }
@tradermatrix
tradermatrix
02 May 2017, 13:32
RE:
Super lucian
A small error and serious consequences but thanks to your help I will be able to modify my cbot.
thanks again
lucian said:
in line 55 , try to use:
if (openedPosition.Label != "Sample" || openedPosition.SymbolCode != _symbol1.Code)instead of:
if (openedPosition.Label != "Sample" || openedPosition.SymbolCode != Symbol.Code)
@tradermatrix
tradermatrix
09 Apr 2017, 16:18
RE:
korakodmy said:
Hello everyone , Now I have cBots , I want to lock account to use for live account not to use public
How to code , Thank you very much
If c is to lock the live accounts (demo available) I can give you an example with a robot
@tradermatrix
tradermatrix
20 Mar 2017, 16:29
RE: RE:
davideng5841@hotmail.com said:
But this version requires 'unlimited access rights', it there any to bypass it ?
Or an error uring bulid ?
Thank you very much,
tradermatrix said:
HI
c's can be better..? with back commissions deducted, to avoid bad surprises...
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo.Robots { [Robot()] public class LIQUIDATE : Robot { [Parameter("TotalProfit", DefaultValue = 5)] public double TotalProfit { get; set; } protected override void OnStart() { string text = "★ Liquidate ★ By TradermatriX ★"; base.ChartObjects.DrawText("★ Liquidate ★ By TradermatriX ★", text, StaticPosition.TopLeft, new Colors?(Colors.Lime)); } protected override void OnTick() { var netProfit = 0.0; foreach (var openedPosition in Positions) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); { if (Account.Equity - Account.Balance > TotalProfit ) { foreach (var openedPosition in Positions) { ClosePosition(openedPosition); foreach (var pendingOrder in PendingOrders) { CancelPendingOrder(pendingOrder); } } } } } } }want to use you for all your post open or l include in a bot.
If you want to include in a bot give me a code and I will help you
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo { [Robot("Sample close profitable positions", TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)] public class SampleCloseProfitablePositionscBot : Robot { [Parameter("TotalProfit", DefaultValue = 5)] public double TotalProfit { get; set; } protected override void OnStart() { string text = "★ Liquidate ★ By TradermatriX ★"; base.ChartObjects.DrawText("★ Liquidate ★ By TradermatriX ★", text, StaticPosition.TopLeft, new Colors?(Colors.Lime)); } protected override void OnTick() { var netProfit = 0.0; foreach (var openedPosition in Positions) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); { if (Account.Equity - Account.Balance > TotalProfit) { foreach (var openedPosition in Positions) { ClosePosition(openedPosition); foreach (var pendingOrder in PendingOrders) { CancelPendingOrder(pendingOrder); } } } } } } }
@tradermatrix
tradermatrix
20 Mar 2017, 14:16
HI
c's can be better..? with back commissions deducted, to avoid bad surprises...
using System; using System.Linq; using cAlgo.API; using cAlgo.API.Indicators; using cAlgo.API.Internals; using cAlgo.Indicators; namespace cAlgo.Robots { [Robot()] public class LIQUIDATE : Robot { [Parameter("TotalProfit", DefaultValue = 5)] public double TotalProfit { get; set; } protected override void OnStart() { string text = "★ Liquidate ★ By TradermatriX ★"; base.ChartObjects.DrawText("★ Liquidate ★ By TradermatriX ★", text, StaticPosition.TopLeft, new Colors?(Colors.Lime)); } protected override void OnTick() { var netProfit = 0.0; foreach (var openedPosition in Positions) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); { if (Account.Equity - Account.Balance > TotalProfit ) { foreach (var openedPosition in Positions) { ClosePosition(openedPosition); foreach (var pendingOrder in PendingOrders) { CancelPendingOrder(pendingOrder); } } } } } } }
@tradermatrix
tradermatrix
06 Mar 2017, 11:15
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 PayBack : Robot { /////////////////////////////////////////////////////// [Parameter("SETTING BUY", DefaultValue = "___BUY___")] public string Separator1 { get; set; } ////////////////////////////////////////////////////// [Parameter("Start Buy", DefaultValue = true)] public bool Buy { get; set; } [Parameter("Quantity initial Buy (Lots)", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double Quantity1 { get; set; } [Parameter("Stop Loss", DefaultValue = 60)] public double StopLoss { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public double TakeProfit { get; set; } [Parameter("Start Martingale Buy", DefaultValue = true)] public bool StartMartingaleBuy { get; set; } [Parameter("Change the direction Martingale", DefaultValue = true)] public bool change1 { get; set; } [Parameter("Multiplier", DefaultValue = 2.1)] public double Multiplier { get; set; } [Parameter("Max Volume Martingale Buy", DefaultValue = 3.2, MinValue = 0.01, Step = 0.01)] public double Quantity1Max { get; set; } [Parameter("Start Automate Buy", DefaultValue = true)] public bool StartAutomate1 { get; set; } /////////////////////////////////////////////////////// [Parameter("SETTING SELL", DefaultValue = "___SELL___")] public string Separator2 { get; set; } ////////////////////////////////////////////////////// [Parameter("Start Sell", DefaultValue = false)] public bool Sell { get; set; } [Parameter("Quantity initial Sell (Lots)", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double Quantity2 { get; set; } [Parameter("Stop Loss", DefaultValue = 60)] public double StopLoss2 { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public double TakeProfit2 { get; set; } [Parameter("Start Martingale Sell", DefaultValue = true)] public bool StartMartingaleSell { get; set; } [Parameter("change the direction Martingale", DefaultValue = false)] public bool change2 { get; set; } [Parameter("Multiplier", DefaultValue = 2.1)] public double Multiplier2 { get; set; } [Parameter("Max Volume Martingale Sell", DefaultValue = 1.2, MinValue = 0.01, Step = 0.01)] public double Quantity2Max { get; set; } [Parameter("Start Automate Sell", DefaultValue = false)] public bool StartAutomate2 { get; set; } /////////////////////////////////////////////////////////////////////////// public long volumeMax1; public long volumeMax2; public double earn1; public double earn2; protected override void OnStart() { string text = "PayBacK By TraderMatriX"; base.ChartObjects.DrawText("PayBacK By TraderMatriX", text, StaticPosition.TopCenter, new Colors?(Colors.Lime)); buy(); Positions.Closed += OnPositionsClosed1; Positions.Closed += OnPositionsClosed2; Positions.Closed += OnPositionsClosedReturnBuy; sell(); Positions.Closed += OnPositionsClosed3; Positions.Closed += OnPositionsClosed4; Positions.Closed += OnPositionsClosedReturnSell; var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max); volumeMax1 = volumeInUnits1Max; var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max); volumeMax2 = volumeInUnits2Max; DisplayEarn(); } protected override void OnTick() { var netProfit = 0.0; foreach (var openedPosition in Positions) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); DisplayEarn(); NetProfit1(); NetProfit2(); } private string GenerateText() { var e1 = ""; var e2 = ""; var earnText = ""; e1 = "\nBuy = " + earn1; e2 = "\nSell = " + earn2; earnText = e1 + e2; return (earnText); } private void DisplayEarn() { ChartObjects.DrawText("text", GenerateText(), StaticPosition.TopRight, Colors.Aqua); } private void NetProfit1() { earn1 = 0; foreach (var pos in Positions) { if (pos.Label.StartsWith("buy PayBack")) { earn1 += pos.NetProfit + pos.Commissions; } } } private void NetProfit2() { earn2 = 0; foreach (var pos2 in Positions) { if (pos2.Label.StartsWith("sell PayBack")) { earn2 += pos2.NetProfit + pos2.Commissions; } } } private void buy() { if (Buy == true) { var cBotPositions = Positions.FindAll("buy PayBack"); if (cBotPositions.Length >= 1) return; var volumeInUnits1 = Symbol.QuantityToVolume(Quantity1); ExecuteMarketOrder(TradeType.Buy, Symbol, volumeInUnits1, "buy PayBack", StopLoss, TakeProfit); Print("ExecuteMarketOrder,Quantity initial Buy"); } } private void sell() { if (Sell == true) { var cBotPositions = Positions.FindAll("sell PayBack"); if (cBotPositions.Length >= 1) return; var volumeInUnits2 = Symbol.QuantityToVolume(Quantity2); ExecuteMarketOrder(TradeType.Sell, Symbol, volumeInUnits2, "sell PayBack", StopLoss2, TakeProfit2); Print("ExecuteMarketOrder,Quantity initial Sell"); } } private void OnPositionsClosed1(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == true) { Print("martingale active + Automate Active...buy PayBack"); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) buy(); { if (position.GrossProfit < 0) { if (change1 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss;inverse direction buy PayBack"); } else if (change1 == false) { TradeType BB = TradeType.Sell; BB = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; NO inverse direction buy PayBack"); } } } } } private void OnPositionsClosed2(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == false) { Print("martingale active + Automate inactive...buy PayBack"); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) return; { if (position.GrossProfit < 0) { if (change1 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; inverse direction buy PayBack"); } else if (change1 == false) { TradeType BB = TradeType.Sell; BB = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; NO inverse direction buy PayBack"); } } } } } private void OnPositionsClosedReturnBuy(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == true) { var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Volume * Multiplier >= volumeInUnits1Max) buy(); } } private void OnPositionsClosed3(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == true) { Print("martingale active + Automate Active...sell PayBack"); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) sell(); { if (position.GrossProfit < 0) { if (change2 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; inverse direction sell PayBack"); } else if (change2 == false) { TradeType BB = TradeType.Buy; BB = TradeType.Sell; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; NO inverse direction sell PayBack"); } } } } } private void OnPositionsClosed4(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == false) { Print("martingale active + Automate inactive...sell PayBack"); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) return; { if (position.GrossProfit < 0) { if (change2 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; inverse direction sell PayBack"); } else if (change2 == false) { TradeType BB = TradeType.Buy; BB = TradeType.Sell; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; NO inverse direction sell PayBack"); } } } } } private void OnPositionsClosedReturnSell(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == true) { var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Volume * Multiplier2 >= volumeInUnits2Max) if (position.GrossProfit < 0) sell(); } } } }
@tradermatrix
tradermatrix
01 Mar 2017, 10:40
Hello
This is normal because you have coded "randomly"
After each closing it starts at random buy or sell
private Random random = new Random();
protected override void OnStart()
{
// Put your initialization logic here
ExecuteOrder(Parameter, GetRandomTradeType());
}
private void CloseAll()
{
foreach (var position in Positions)
{
ClosePosition(position);
}
negsellscope = 0;
negbuyscope = 0;
grouptrades++;
var volumeInUnits = Symbol.QuantityToVolume(Quantity);
ExecuteOrder(volumeInUnits, GetTradeCommand());
}
You can do a hundred times the backtesting it will always be different ..
I have replaced "random" by an indicator and it works well..the backtesting is regular.
good trades
@+
@tradermatrix
tradermatrix
17 Feb 2017, 15:15
Hello
I have cut a piece of my bot code
You can choose the direction that wish you to buy or sell.
and even reverse the direction of the losing trades
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 PayBack : Robot { /////////////////////////////////////////////////////// [Parameter("SETTING BUY", DefaultValue = "___BUY___")] public string Separator1 { get; set; } ////////////////////////////////////////////////////// [Parameter("Start Buy", DefaultValue = true)] public bool Buy { get; set; } [Parameter("Quantity initial Buy (Lots)", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double Quantity1 { get; set; } [Parameter("Stop Loss", DefaultValue = 60)] public double StopLoss { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public double TakeProfit { get; set; } [Parameter("Start Martingale Buy", DefaultValue = true)] public bool StartMartingaleBuy { get; set; } [Parameter("Change the direction Martingale", DefaultValue = false)] public bool change1 { get; set; } [Parameter("Multiplier", DefaultValue = 2.1)] public double Multiplier { get; set; } [Parameter("Max Volume Martingale Buy", DefaultValue = 1.2, MinValue = 0.01, Step = 0.01)] public double Quantity1Max { get; set; } [Parameter("Start Automate Buy", DefaultValue = false)] public bool StartAutomate1 { get; set; } /////////////////////////////////////////////////////// [Parameter("SETTING SELL", DefaultValue = "___SELL___")] public string Separator2 { get; set; } ////////////////////////////////////////////////////// [Parameter("Start Sell", DefaultValue = false)] public bool Sell { get; set; } [Parameter("Quantity initial Sell (Lots)", DefaultValue = 0.1, MinValue = 0.01, Step = 0.01)] public double Quantity2 { get; set; } [Parameter("Stop Loss", DefaultValue = 60)] public double StopLoss2 { get; set; } [Parameter("Take Profit", DefaultValue = 80)] public double TakeProfit2 { get; set; } [Parameter("Start Martingale Sell", DefaultValue = true)] public bool StartMartingaleSell { get; set; } [Parameter("change the direction Martingale", DefaultValue = false)] public bool change2 { get; set; } [Parameter("Multiplier", DefaultValue = 2.1)] public double Multiplier2 { get; set; } [Parameter("Max Volume Martingale Sell", DefaultValue = 1.2, MinValue = 0.01, Step = 0.01)] public double Quantity2Max { get; set; } [Parameter("Start Automate Sell", DefaultValue = false)] public bool StartAutomate2 { get; set; } /////////////////////////////////////////////////////////////////////////// public long volumeMax1; public long volumeMax2; public double earn1; public double earn2; protected override void OnStart() { string text = "PayBacK By TraderMatriX"; base.ChartObjects.DrawText("PayBacK By TraderMatriX", text, StaticPosition.TopCenter, new Colors?(Colors.Lime)); buy(); Positions.Closed += OnPositionsClosed1; Positions.Closed += OnPositionsClosed2; Positions.Closed += OnPositionsClosedReturnBuy; sell(); Positions.Closed += OnPositionsClosed3; Positions.Closed += OnPositionsClosed4; Positions.Closed += OnPositionsClosedReturnSell; var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max); volumeMax1 = volumeInUnits1Max; var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max); volumeMax2 = volumeInUnits2Max; DisplayEarn(); } protected override void OnTick() { var netProfit = 0.0; foreach (var openedPosition in Positions) { netProfit += openedPosition.NetProfit + openedPosition.Commissions; } ChartObjects.DrawText("a", netProfit.ToString(), StaticPosition.BottomRight, new Colors?(Colors.Lime)); DisplayEarn(); NetProfit1(); NetProfit2(); } private string GenerateText() { var e1 = ""; var e2 = ""; var earnText = ""; e1 = "\nBuy = " + earn1; e2 = "\nSell = " + earn2; earnText = e1 + e2; return (earnText); } private void DisplayEarn() { ChartObjects.DrawText("text", GenerateText(), StaticPosition.TopRight, Colors.Aqua); } private void NetProfit1() { earn1 = 0; foreach (var pos in Positions) { if (pos.Label.StartsWith("buy PayBack")) { earn1 += pos.NetProfit + pos.Commissions; } } } private void NetProfit2() { earn2 = 0; foreach (var pos2 in Positions) { if (pos2.Label.StartsWith("sell PayBack")) { earn2 += pos2.NetProfit + pos2.Commissions; } } } private void buy() { if (Buy == true) { var cBotPositions = Positions.FindAll("buy PayBack"); if (cBotPositions.Length >= 1) return; var volumeInUnits1 = Symbol.QuantityToVolume(Quantity1); ExecuteMarketOrder(TradeType.Buy, Symbol, volumeInUnits1, "buy PayBack", StopLoss, TakeProfit); Print("ExecuteMarketOrder,Quantity initial Buy"); } } private void sell() { if (Sell == true) { var cBotPositions = Positions.FindAll("sell PayBack"); if (cBotPositions.Length >= 1) return; var volumeInUnits2 = Symbol.QuantityToVolume(Quantity2); ExecuteMarketOrder(TradeType.Sell, Symbol, volumeInUnits2, "sell PayBack", StopLoss2, TakeProfit2); Print("ExecuteMarketOrder,Quantity initial Sell"); } } private void OnPositionsClosed1(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == true) { Print("martingale active + Automate Active...buy PayBack"); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) buy(); { if (position.GrossProfit < 0) { if (change1 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss;inverse direction buy PayBack"); } else if (change1 == false) { TradeType BB = TradeType.Sell; BB = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; NO inverse direction buy PayBack"); } } } } } private void OnPositionsClosed2(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == false) { Print("martingale active + Automate inactive...buy PayBack"); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) return; { if (position.GrossProfit < 0) { if (change1 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; inverse direction buy PayBack"); } else if (change1 == false) { TradeType BB = TradeType.Sell; BB = TradeType.Buy; if (position.Volume * Multiplier <= volumeMax1) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier), "buy PayBack", StopLoss, TakeProfit); Print("loss; NO inverse direction buy PayBack"); } } } } } private void OnPositionsClosedReturnBuy(PositionClosedEventArgs args) { if (Buy == true) if (StartMartingaleBuy == true) if (StartAutomate1 == true) { var volumeInUnits1Max = Symbol.QuantityToVolume(Quantity1Max); var position = args.Position; if (position.Label != "buy PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Volume * Multiplier >= volumeInUnits1Max) buy(); } } private void OnPositionsClosed3(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == true) { Print("martingale active + Automate Active...sell PayBack"); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) sell(); { if (position.GrossProfit < 0) { if (change2 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; inverse direction sell PayBack"); } else if (change2 == false) { TradeType BB = TradeType.Buy; BB = TradeType.Sell; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; NO inverse direction sell PayBack"); } } } } } private void OnPositionsClosed4(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == false) { Print("martingale active + Automate inactive...sell PayBack"); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Pips > 0) return; { if (position.GrossProfit < 0) { if (change2 == true) { TradeType AA = TradeType.Sell; if (position.TradeType == TradeType.Sell) AA = TradeType.Buy; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(AA, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; inverse direction sell PayBack"); } else if (change2 == false) { TradeType BB = TradeType.Buy; BB = TradeType.Sell; if (position.Volume * Multiplier2 <= volumeMax2) ExecuteMarketOrder(BB, Symbol, Symbol.NormalizeVolume(position.Volume * Multiplier2), "sell PayBack", StopLoss2, TakeProfit2); Print("loss; NO inverse direction sell PayBack"); } } } } } private void OnPositionsClosedReturnSell(PositionClosedEventArgs args) { if (Sell == true) if (StartMartingaleSell == true) if (StartAutomate2 == true) { var volumeInUnits2Max = Symbol.QuantityToVolume(Quantity2Max); var position = args.Position; if (position.Label != "sell PayBack" || position.SymbolCode != Symbol.Code) return; if (position.Volume * Multiplier2 >= volumeInUnits2Max) if (position.GrossProfit < 0) sell(); } } } }
@tradermatrix
tradermatrix
28 Nov 2016, 21:51
hi
Start if trigger > 0
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 SampleTrend : Robot { [Parameter("MA Type")] public MovingAverageType MAType { get; set; } [Parameter()] public DataSeries SourceSeries { get; set; } [Parameter("Slow Periods", DefaultValue = 65)] public int SlowPeriods { get; set; } [Parameter("Fast Periods", DefaultValue = 15)] public int FastPeriods { get; set; } [Parameter("Quantity (Lots)", DefaultValue = 1, MinValue = 0.01, Step = 0.01)] public double Quantity { get; set; } [Parameter("Stop Loss (pips)", DefaultValue = 20, MinValue = 1)] public int StopLossInPips { get; set; } [Parameter("Take Profit (pips)", DefaultValue = 60, MinValue = 1)] public int TakeProfitInPips { get; set; } [Parameter("trigger ", DefaultValue = 20)] public int Trigger { get; set; } [Parameter("Trailing", DefaultValue = 10)] public int Trailing { get; set; } private MovingAverage slowMa; private MovingAverage fastMa; private const string label = "Sample Trend cBot"; protected override void OnStart() { fastMa = Indicators.MovingAverage(SourceSeries, FastPeriods, MAType); slowMa = Indicators.MovingAverage(SourceSeries, SlowPeriods, MAType); } protected override void OnTick() { TRAILING(); { var longPosition = Positions.Find(label, Symbol, TradeType.Buy); var shortPosition = Positions.Find(label, Symbol, TradeType.Sell); var currentSlowMa = slowMa.Result.Last(0); var currentFastMa = fastMa.Result.Last(0); var previousSlowMa = slowMa.Result.Last(1); var previousFastMa = fastMa.Result.Last(1); if (previousSlowMa > previousFastMa && currentSlowMa <= currentFastMa && longPosition == null) { if (shortPosition != null) ClosePosition(shortPosition); ExecuteMarketOrder(TradeType.Buy, Symbol, VolumeInUnits, label, StopLossInPips, TakeProfitInPips); } else if (previousSlowMa < previousFastMa && currentSlowMa >= currentFastMa && shortPosition == null) { if (longPosition != null) ClosePosition(longPosition); ExecuteMarketOrder(TradeType.Sell, Symbol, VolumeInUnits, label, StopLossInPips, TakeProfitInPips); } } } private void TRAILING() { if (Trailing > 0 && Trigger > 0) { Position[] positions = Positions.FindAll(label, Symbol); foreach (Position position in positions) { if (position.TradeType == TradeType.Sell) { double distance = position.EntryPrice - Symbol.Ask; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Ask + Trailing * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice < position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } else { double distance = Symbol.Bid - position.EntryPrice; if (distance >= Trigger * Symbol.PipSize) { double newStopLossPrice = Symbol.Bid - Trailing * Symbol.PipSize; if (position.StopLoss == null || newStopLossPrice > position.StopLoss) { ModifyPosition(position, newStopLossPrice, position.TakeProfit); } } } } } } private long VolumeInUnits { get { return Symbol.QuantityToVolume(Quantity); } } } }
@tradermatrix
tradermatrix
22 Mar 2018, 18:39
thank you sir
for example
with spotware ... and the same parameters as above
table 2 minutes
backtesting tick data
from 01 09 2017 to 20 03 2018
crashed 22 09 at 20:59:56
@tradermatrix