public override void Initialize(BacktestServerProxy.RobotContext robotContext, CurrentProtectedContext protectedContext) { base.Initialize(robotContext, protectedContext); if (Graphics.Count == 0) return; packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); pointCost = Graphics.ToDictionary(g => g.a, g => DalSpot.Instance.GetAbsValue(g.a, 1M)); lastCandles = Graphics.ToDictionary(g => g.a, g => new List<CandleData>()); }
public TradeSignalProcessor(Func<Account> getAccountInfo, Action<string> logMessage, Func<List<MarketOrder>> getMarketOrders, Func<VolumeRoundType> getVolumeRound, ITradeSharpServerTrade proxy, CurrentProtectedContext protectedContext, FarmAccount farmAccount) { this.getAccountInfo = getAccountInfo; this.proxy = proxy; this.logMessage = logMessage; this.getMarketOrders = getMarketOrders; this.getVolumeRound = getVolumeRound; this.protectedContext = protectedContext; this.farmAccount = farmAccount; }
public override void Initialize(RobotContext context, CurrentProtectedContext protectedContext) { var cfgFileName = Assembly.GetAssembly(GetType()).Location + ".xml"; string error; newsSettings = NewsSettings.LoadNewsSettings(cfgFileName, out error); if (error != null) pendingLogMessages.Add(error); currencySettings = CurrencySettings.LoadCurrencySettings(cfgFileName, out error); if (error != null) pendingLogMessages.Add(error); if(string.IsNullOrEmpty(Formula)) pendingLogMessages.Add("формула не задана"); try { expressionResolver = new ExpressionResolver(Formula.ToLower()); } catch (Exception) { pendingLogMessages.Add("ошибка в формуле"); } base.Initialize(context, protectedContext); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("Atracotes MTS: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("Atracotes MTS: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; lastBids = new Dictionary<string, double>(); foreach (var ind in IndexList) { ind.Initialize(); ind.lastIndicies = new List<double>(); ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>(); } candles = new List<CandleData>(); packer = new CandlePacker(Graphics[0].b); var levels = FiboLevels.ToFloatArrayUniform(); fiboLevels.Clear(); foreach (var level in levels) { try { fiboLevels.Add(level); } catch (FormatException) { } } tickerNames = DalSpot.Instance.GetTickerNames(); randomGener = new Random(DateTime.Now.Millisecond); lastBidLists = new Dictionary<string, List<double>>(); // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса) InitLastBidLists(); //RobotTradeState = TradeState.НетПозиций; stopsOnPositions = StopPositionsState.Незащищены; TerminalLog.Instance.SaveRobotLog("Atracotes MTS: RobotTradeState = " + RobotTradeState); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("StopRobot: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("StopRobot: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; packer = new CandlePacker(Graphics[0].b); }
public override void Initialize(BacktestServerProxy.RobotContext robotContext, CurrentProtectedContext protectedContext) { base.Initialize(robotContext, protectedContext); if (Graphics.Count == 0) { return; } packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); pointCost = Graphics.ToDictionary(g => g.a, g => DalSpot.Instance.GetAbsValue(g.a, 1M)); candlesStoredCount = Math.Max(MovAvgPeriod, MomentumPeriod); storedCandles = Graphics.ToDictionary(g => g.a, g => new List <CandleData>(candlesStoredCount)); storedMovAvg = Graphics.ToDictionary(g => g.a, g => new List <int>(3)); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext xprotectedContext) { base.Initialize(grobotContext, xprotectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("MultiIndexRobot: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("MultiIndexRobot: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; timeframe = Graphics[0].b; lastBids = new Dictionary<string, double>(); foreach (var ind in IndexList) { ind.Initialize(); ind.lastIndicies = new List<double>(); ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>(); } candles = new List<CandleData>(); packer = new CandlePacker(Graphics[0].b); tickerNames = DalSpot.Instance.GetTickerNames(); randomGener = new Random(DateTime.Now.Millisecond); lastBidLists = new Dictionary<string, List<double>>(); // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса) InitLastBidLists(); }
public override void Initialize(RobotContext grobotContext, CurrentProtectedContext gprotectedContext) { base.Initialize(grobotContext, gprotectedContext); packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); rsiClosePairs = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue<PriceRsi>(period)); lastMessages = new List<string>(); }
public void StopProcessing() { // деинициализировать роботов foreach (var robot in robots) { try { robot.DeInitialize(); context.UnsubscribeRobot(robot); } catch (Exception ex) { Logger.Error("Ошибка останова робота " + robot.GetUniqueName() + ":", ex); } } // выполнить логаут и закрыть прокси try { context.Logout(protectedContext.MakeProtectedContext()); } catch (Exception ex) { Logger.Error("Ошибка закрытия контекста счета " + AccountId, ex); } protectedContext = null; }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); initMessageWasSent = false; timeSinceUpdate.Touch(); ordersFromMt4.ExtractAll(1000*10); ordersFromMt4Received = false; sentRequests.ExtractAll(1000*10); // стартовать прослушку порта try { var e = new IPEndPoint(IPAddress.Parse(hostMt4), portOwn); client = new UdpClient(e); client.BeginReceive(ReceiveCallback, null); } catch (ArgumentOutOfRangeException) { errorMessage = string.Format("MT4 транслятор: порт ({0}) задан неверно. Допустимый диапазон: {1} - {2}", portOwn, IPEndPoint.MinPort, IPEndPoint.MaxPort); client = null; return; } catch (Exception ex) { client = null; errorMessage = string.Format("MT4 транслятор: ошибка прослушивания порта ({0}): {1}", portOwn, ex.Message); } // стратовать поток отправки команд commandSendThread = new Thread(CommandSendRoutine); commandSendThread.Start(); }
public override void Initialize(RobotContext robotContext, CurrentProtectedContext protectedContext) { base.Initialize(robotContext, protectedContext); if (Graphics.Count == 0) { Logger.DebugFormat("OptionUpDownMartinRobot: настройки графиков не заданы"); return; } packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); lastCandles = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue<CandleData>(candlesBeforeEnter)); betsBySymbol = Graphics.ToDictionary(g => g.a, g => new List<Bet>()); betsHistory = Graphics.ToDictionary(g => g.a, g => new List<Bet>()); balance = StartDepo; maxBalance = StartDepo; betNumberWhenDepoWasLost = 0; }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("FiboLevelRobot: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("FiboLevelRobot: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; timeframe = Graphics[0].b; packer = new CandlePacker(timeframe); // расчет вспомогательных переменных side = PriceB > PriceA ? 1 : PriceB < PriceA ? -1 : 0; minuteCandlesCount = 0; minuteCandlesBodiesSum = 0; lastBid = 0; timeOfLastCandle = new DateTime(1972, 1, 1); // получить категории торговых сигналов if (ShouldMakePresignals) { currentPresignalPrimeTimes = presignalMinutesToClose.ToList(); var signals = grobotContext is BacktestServerProxy.RobotContextLive ? ((BacktestServerProxy.RobotContextLive)grobotContext).GetAuthoredTradeSignals() : new List<PaidService>(); if (signals.Count > 0) { var signal = signals[0]; if (signal != null) { authoredTradeSignalCategory = signal.Id; Logger.InfoFormat("Робот {0} - отправляет сигналы {1} ({2})", GetUniqueName(), authoredTradeSignalCategory, signal.Comment); } } } // поставить на графике точечки AddRobotHintOnPriceUpdated("A", 0, priceA, TimeOfA); AddRobotHintOnPriceUpdated("B", 0, priceB, TimeOfB); }
public override void Initialize(BacktestServerProxy.RobotContext robotContext, CurrentProtectedContext protectedContext) { base.Initialize(robotContext, protectedContext); if (Graphics.Count == 0) return; packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); pointCost = Graphics.ToDictionary(g => g.a, g => DalSpot.Instance.GetAbsValue(g.a, 1M)); candlesStoredCount = Math.Max(MovAvgPeriod, MomentumPeriod); storedCandles = Graphics.ToDictionary(g => g.a, g => new List<CandleData>(candlesStoredCount)); storedMovAvg = Graphics.ToDictionary(g => g.a, g => new List<int>(3)); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("FibonacciRobot: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("FibonacciRobot: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; packer = new CandlePacker(Graphics[0].b); candles = new List<CandleData>(); pointPrice = 1M/DalSpot.Instance.GetPrecision10(ticker); //fiboDistanceAbs = FiboReachDistancePoint*pointPrice; markedZigZagPivots = new List<int>(); }
public override void Initialize(RobotContext grobotContext, CurrentProtectedContext protectedContextx) { base.Initialize(grobotContext, protectedContextx); if (Graphics.Count == 0) { Logger.DebugFormat("OptionTraderRobot: настройки графиков не заданы"); return; } tickers = Graphics.Select(r => r.a).ToArray(); tickerVolatility = tickers.ToDictionary(t => t, t => Model == PriceModel.Gauss ? (IVolatilityCalculator)new GaussVolatilityCalculator(200) : new ReverseVolatilityCalculator(1000)); }
public bool SetupLiveContext() { context = null; protectedContext = new CurrentProtectedContext(); try { protectedContext.Initialize(TerminalId); } catch (Exception ex) { Logger.Error("Ошибка инициализации защищенного контекста", ex); throw; } // создать объект proxy try { if (proxyTrade == null) proxyTrade = new TradeSharpServerTrade(callbackProcessor); } catch (Exception ex) { RobotFarm.Instance.AppendLogMessage("Ошибка создания TradeSharpServerTrade: " + ex); return false; } // залогиниться и // получить актуальную информацию по счету Account account; try { var localTime = DateTime.Now.Ticks; var hash = CredentialsHash.MakeCredentialsHash(UserLogin, UserPassword, localTime); int sessionTag; var response = proxyTrade.proxy.Authenticate(UserLogin, hash, TerminalVersionString, TerminalId, localTime, out sessionTag); if (response != AuthenticationResponse.OK) { protectedContext.OnAuthenticateFaulted(); RobotFarm.Instance.AppendLogMessage(string.Format("Ошибка аутентификации ({0}-{1}): {2}", UserLogin, UserPassword, response)); return false; } protectedContext.OnAuthenticated(sessionTag); var opRst = TradeSharpAccount.Instance.proxy.GetAccountInfo(AccountId, false, out account); if (account == null) { RobotFarm.Instance.AppendLogMessage(string.Format("Невозможно получить информацию по счету {0}: {1}", AccountId, opRst)); return false; } Logger.InfoFormat("User {0} authenticated on #{1}", UserLogin, AccountId); } catch (Exception ex) { RobotFarm.Instance.AppendLogMessage( string.Format("Ошибка аутентификации ({0}-{1}): {2}", UserLogin, UserPassword, ex)); return false; } // инициализировать киборгов var countSuccess = robots == null ? 0 : robots.Count; if (robots != null && robots.Count > 0) { // контекст для роботов context = new RobotContextLiveFarm(proxyTrade, account, () => UserLogin, accountData) { robotContextMode = RobotContext.ContextMode.Realtime }; context.OnRobotMessage += (robot, time, messages) => { foreach (var msg in messages) RobotFarm.Instance.AppendLogMessage( "#" + AccountId + ": [" + robot.GetUniqueName() + "] said \"" + msg + "\""); }; // включить каждого робота в контекст foreach (var robot in robots) { try { robot.Initialize(context, protectedContext); context.SubscribeRobot(robot); } catch (Exception ex) { countSuccess--; RobotFarm.Instance.AppendLogMessage("Ошибка инициализации робота " + robot.GetUniqueName() + ": " + ex); } } } // создать объект - обработчик торговых сигалов callbackProcessor.SignalProcessor = new TradeSignalProcessor( () => accountData.GetActualAccount(true), s => RobotFarm.Instance.AppendLogMessage(s), () => accountData.GetActualOrderList(), () => VolumeRoundType.Ближайшее, proxyTrade.proxy, protectedContext, this); return (robots == null || robots.Count <= 0) || countSuccess > 0; }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContextx) { base.Initialize(grobotContext, protectedContextx); if (Graphics.Count == 0) { Logger.DebugFormat("RobotMA: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("RobotMA: настройки графиков должны описывать один тикер / один ТФ"); return; } packer = new CandlePacker(Graphics[0].b); ticker = Graphics[0].a; maDifSign = 0; queueSlow = new RestrictedQueue<float>(RangeSlowMA); queueFast = new RestrictedQueue<float>(RangeFastMA); virtualDeal = null; prevSign = 0; virtualResults = new RestrictedQueue<float>(PeriodVirtualResults); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); // проверка настроек графиков if (Graphics.Count == 0) { Logger.DebugFormat("MultiIndexRobot: настройки графиков не заданы"); return; } if (Graphics.Count > 1) { Logger.DebugFormat("MultiIndexRobot: настройки графиков должны описывать один тикер / один ТФ"); return; } ticker = Graphics[0].a; lastBids = new Dictionary<string, double>(); foreach (var ind in DiversToEnter) { ind.Initialize(); ind.lastIndicies = new List<double>(); ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>(); } foreach (var protectSets in DiversToProtect) foreach (var ind in protectSets.IndexList) { ind.Initialize(); ind.lastIndicies = new List<double>(); ind.indexPeaks = new List<Cortege3<decimal, int, decimal>>(); } foreach (var filter in filters) filter.Initialize(); candles = new List<CandleData>();//CandlesInIndexHistory); packer = new CandlePacker(Graphics[0].b); packerDiverProtect = diversToProtect.Count == 0 ? null : diversToProtect.ToDictionary(d => d, d => new CandlePacker(d.timeframe)); candles4Protect = diversToProtect.Count == 0 ? null : diversToProtect.ToDictionary(d => d, d => new List<CandleData>()); tickerNames = DalSpot.Instance.GetTickerNames(); randomGener = new Random(DateTime.Now.Millisecond); lastBidLists = new Dictionary<string, List<double>>(); // по каждой валютной паре найти макс. количество отсчетов (из формулы индекса) InitLastBidLists(); if (CalcDealChainStat) { dealChainStat = new List<int>(); } }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); depoWarning = HighWaterMark*(1 - PercentYellow/100M); depoStopout = HighWaterMark*(1 - PercentRed/100M); lastCheckTime = null; lastState = StateCode.OK; orderStorage = new MarketOrderSafeStorage(1000, 10 * 1000, grobotContext); }
public override void Initialize(BacktestServerProxy.RobotContext robotContext, CurrentProtectedContext protectedContext) { base.Initialize(robotContext, protectedContext); if (Graphics.Count == 0) return; packers = Graphics.ToDictionary(g => g.a, g => new CandlePacker(g.b)); pointCost = Graphics.ToDictionary(g => g.a, g => DalSpot.Instance.GetAbsValue(g.a, 1M)); storedCandles = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue<CandleData>(CandlesToDetermineAverage)); bollingerSignalHistory = Graphics.ToDictionary(g => g.a, g => new RestrictedQueue<int>(CandlesAfter)); }
public override void Initialize(BacktestServerProxy.RobotContext grobotContext, CurrentProtectedContext protectedContext) { base.Initialize(grobotContext, protectedContext); tickers = Graphics.Select(g => g.a).ToArray(); }
/// <summary> /// This method is used to configure the strategy and is called once before any strategy method is called. /// </summary> public virtual void Initialize(RobotContext robotContext, CurrentProtectedContext protectedContext) { this.protectedContext = protectedContext; this.robotContext = robotContext; TerminalLog.Instance.SaveRobotLog(string.Format("Запущен робот {0} #{1}", GetUniqueName(), robotContext.AccountInfo.ID)); if ((FixedVolume ?? 0) <= 0 && (Leverage ?? 0) <= 0) if (lastMessages != null) lastMessages.Add("Не указаны ни плечо сделки, ни фиксированный объем входа. Торговля осуществляться не будет"); }
public bool SetupLiveContext() { context = null; protectedContext = new CurrentProtectedContext(); try { protectedContext.Initialize(TerminalId); } catch (Exception ex) { Logger.Error("Ошибка инициализации защищенного контекста", ex); throw; } // создать объект proxy try { if (proxyTrade == null) { proxyTrade = new TradeSharpServerTrade(callbackProcessor); } } catch (Exception ex) { RobotFarm.Instance.AppendLogMessage("Ошибка создания TradeSharpServerTrade: " + ex); return(false); } // залогиниться и // получить актуальную информацию по счету Account account; try { var localTime = DateTime.Now.Ticks; var hash = CredentialsHash.MakeCredentialsHash(UserLogin, UserPassword, localTime); int sessionTag; var response = proxyTrade.proxy.Authenticate(UserLogin, hash, TerminalVersionString, TerminalId, localTime, out sessionTag); if (response != AuthenticationResponse.OK) { protectedContext.OnAuthenticateFaulted(); RobotFarm.Instance.AppendLogMessage(string.Format("Ошибка аутентификации ({0}-{1}): {2}", UserLogin, UserPassword, response)); return(false); } protectedContext.OnAuthenticated(sessionTag); var opRst = TradeSharpAccount.Instance.proxy.GetAccountInfo(AccountId, false, out account); if (account == null) { RobotFarm.Instance.AppendLogMessage(string.Format("Невозможно получить информацию по счету {0}: {1}", AccountId, opRst)); return(false); } Logger.InfoFormat("User {0} authenticated on #{1}", UserLogin, AccountId); } catch (Exception ex) { RobotFarm.Instance.AppendLogMessage( string.Format("Ошибка аутентификации ({0}-{1}): {2}", UserLogin, UserPassword, ex)); return(false); } // инициализировать киборгов var countSuccess = robots == null ? 0 : robots.Count; if (robots != null && robots.Count > 0) { // контекст для роботов context = new RobotContextLiveFarm(proxyTrade, account, () => UserLogin, accountData) { robotContextMode = RobotContext.ContextMode.Realtime }; context.OnRobotMessage += (robot, time, messages) => { foreach (var msg in messages) { RobotFarm.Instance.AppendLogMessage( "#" + AccountId + ": [" + robot.GetUniqueName() + "] said \"" + msg + "\""); } }; // включить каждого робота в контекст foreach (var robot in robots) { try { robot.Initialize(context, protectedContext); context.SubscribeRobot(robot); } catch (Exception ex) { countSuccess--; RobotFarm.Instance.AppendLogMessage("Ошибка инициализации робота " + robot.GetUniqueName() + ": " + ex); } } } // создать объект - обработчик торговых сигалов callbackProcessor.SignalProcessor = new TradeSignalProcessor( () => accountData.GetActualAccount(true), s => RobotFarm.Instance.AppendLogMessage(s), () => accountData.GetActualOrderList(), () => VolumeRoundType.Ближайшее, proxyTrade.proxy, protectedContext, this); return((robots == null || robots.Count <= 0) || countSuccess > 0); }