/// <summary> /// set stop orders and profit orders /// выставление стоп-лосс и таке-профит /// </summary> private void Strateg_PositionOpen(Position position) { List <Position> openPositions = _tab.PositionsOpenAll; for (int i = 0; openPositions != null && i < openPositions.Count; i++) { if (openPositions[i].Direction == Side.Buy) { decimal lowCandle = _tab.CandlesAll[_tab.CandlesAll.Count - 2].Low; _tab.CloseAtStop(openPositions[i], lowCandle, lowCandle - Slippage.ValueInt * _tab.Securiti.PriceStep); _tab.CloseAtProfit( openPositions[i], _lastPrice + (_lastPcUp - _lastPcDown), (_lastPrice + (_lastPcUp - _lastPcDown)) - Slippage.ValueInt * _tab.Securiti.PriceStep); } else { decimal highCandle = _tab.CandlesAll[_tab.CandlesAll.Count - 2].High; _tab.CloseAtStop(openPositions[i], highCandle, highCandle + Slippage.ValueInt * _tab.Securiti.PriceStep); _tab.CloseAtProfit( openPositions[i], _lastPrice - (_lastPcUp - _lastPcDown), (_lastPrice - (_lastPcUp - _lastPcDown)) + Slippage.ValueInt * _tab.Securiti.PriceStep); } } }
/// <summary> /// событие открытия новой позиции /// </summary> void _tab_PositionOpeningSuccesEvent(Position position) { if (ProfitOrderIsOn) { if (position.Direction == Side.Buy) { decimal stopPrice = position.EntryPrice + position.EntryPrice * (ProfitOrderValue / 100); decimal stopOrderPrice = stopPrice - _tab.Securiti.PriceStep * ProfitOrderSleepage; _tab.CloseAtProfit(position, stopPrice, stopOrderPrice); } else if (position.Direction == Side.Sell) { decimal stopPrice = position.EntryPrice - position.EntryPrice * (ProfitOrderValue / 100); decimal stopOrderPrice = stopPrice + _tab.Securiti.PriceStep * ProfitOrderSleepage; _tab.CloseAtProfit(position, stopPrice, stopOrderPrice); } } if (StopOrderIsOn) { if (position.Direction == Side.Buy) { decimal stopPrice = position.EntryPrice - position.EntryPrice * (StopOrderValue / 100); decimal stopOrderPrice = stopPrice - _tab.Securiti.PriceStep * StopOrderSleepage; _tab.CloseAtStop(position, stopPrice, stopOrderPrice); } else if (position.Direction == Side.Sell) { decimal stopPrice = position.EntryPrice + position.EntryPrice * (StopOrderValue / 100); decimal stopOrderPrice = stopPrice + _tab.Securiti.PriceStep * StopOrderSleepage; _tab.CloseAtStop(position, stopPrice, stopOrderPrice); } } }
/// <summary> /// successful position opening /// успешное открытие позиции /// </summary> void _tab_PositionOpeningSuccesEvent(Position position) { if (position.Direction == Side.Buy) { _tab.CloseAtStop(position, position.EntryPrice - Stop.ValueInt * _tab.Securiti.PriceStep, position.EntryPrice - Stop.ValueInt * _tab.Securiti.PriceStep); _tab.CloseAtProfit(position, position.EntryPrice + Profit.ValueInt * _tab.Securiti.PriceStep, position.EntryPrice + Profit.ValueInt * _tab.Securiti.PriceStep); } if (position.Direction == Side.Sell) { _tab.CloseAtStop(position, position.EntryPrice + Stop.ValueInt * _tab.Securiti.PriceStep, position.EntryPrice + Stop.ValueInt * _tab.Securiti.PriceStep); _tab.CloseAtProfit(position, position.EntryPrice - Profit.ValueInt * _tab.Securiti.PriceStep, position.EntryPrice - Profit.ValueInt * _tab.Securiti.PriceStep); } List <Position> positions = _tab.PositionsOpenAll; for (int i = 0; i < positions.Count; i++) { if (positions[i].Number == position.Number) { continue; } if (StartProgram == StartProgram.IsOsTrader) { _positionsToClose.Add(positions[i]); } else { _tab.CloseAllOrderToPosition(positions[i]); } } }
private void Strateg_PositionOpen(Position position) { _tab.SellAtStopCancel(); _tab.BuyAtStopCancel(); List <Position> openPositions = _tab.PositionsOpenAll; for (int i = 0; openPositions != null && i < openPositions.Count; i++) { if (openPositions[i].Direction == Side.Buy) { _tab.SellAtStopCancel(); decimal stop = GetLastFractail(Fractail.DataSeries.ByName("SeriesDown")); _tab.CloseAtStop(openPositions[i], stop, stop - Slipage.ValueDecimal); // _tab.CloseAtStop(openPositions[i], _tab.CandlesAll[_tab.CandlesAll.Count-1].Low, _tab.CandlesAll[_tab.CandlesAll.Count - 1].Low - Slipage.ValueDecimal); // _tab.CloseAtProfit(openPositions[i], openPositions[i].EntryPrice + _lastAtr, openPositions[i].EntryPrice + _lastAtr - Slipage.ValueDecimal); } else { _tab.BuyAtStopCancel(); decimal stop = GetLastFractail(Fractail.DataSeries.ByName("SeriesUp")); _tab.CloseAtStop(openPositions[i], stop, stop + Slipage.ValueDecimal); // _tab.CloseAtStop(openPositions[i], _tab.CandlesAll[_tab.CandlesAll.Count - 1].High, _tab.CandlesAll[_tab.CandlesAll.Count - 1].High + Slipage.ValueDecimal); // _tab.CloseAtProfit(openPositions[i], openPositions[i].EntryPrice - _lastAtr, openPositions[i].EntryPrice - _lastAtr + Slipage.ValueDecimal); } } }
private void TabOnPositionOpeningSuccesEvent(Position position) { decimal stopPrice = 0; decimal stopActivationPrice = 0; decimal profitPrice = 0; decimal profitActivationPrice = 0; if (position.Direction == Side.Buy) { stopPrice = position.EntryPrice - position.EntryPrice * (Stop.ValueDecimal / 100); stopActivationPrice = stopPrice - stopPrice * (Slippage.ValueDecimal / 100); profitPrice = position.EntryPrice + position.EntryPrice * (Profit.ValueDecimal / 100); profitActivationPrice = profitPrice - stopPrice * (Slippage.ValueDecimal / 100); } if (position.Direction == Side.Sell) { stopPrice = position.EntryPrice + position.EntryPrice * (Stop.ValueDecimal / 100); stopActivationPrice = stopPrice + stopPrice * (Slippage.ValueDecimal / 100); profitPrice = position.EntryPrice - position.EntryPrice * (Profit.ValueDecimal / 100); profitActivationPrice = profitPrice + stopPrice * (Slippage.ValueDecimal / 100); } _tab.CloseAtStop(position, stopActivationPrice, stopPrice); _tab.CloseAtProfit(position, profitActivationPrice, profitPrice); }
public void TryReloadStopAndProfit(BotTabSimple bot, Position position) { if (StopIsOn) { if (position.Direction == Side.Buy) { decimal priceRedLine = position.EntryPrice - GetStopDistance(position, bot.Securiti); decimal priceOrder = priceRedLine - GetStopSlippageDistance(position, bot.Securiti); bot.CloseAtStop(position, priceRedLine, priceOrder); } if (position.Direction == Side.Sell) { decimal priceRedLine = position.EntryPrice + GetStopDistance(position, bot.Securiti); decimal priceOrder = priceRedLine + GetStopSlippageDistance(position, bot.Securiti); bot.CloseAtStop(position, priceRedLine, priceOrder); } } if (ProfitIsOn) { if (position.Direction == Side.Buy) { decimal priceRedLine = position.EntryPrice + GetProfitDistance(position, bot.Securiti); decimal priceOrder = priceRedLine - GetProfitDistanceSlippage(position, bot.Securiti); bot.CloseAtProfit(position, priceRedLine, priceOrder); } if (position.Direction == Side.Sell) { decimal priceRedLine = position.EntryPrice - GetProfitDistance(position, bot.Securiti); decimal priceOrder = priceRedLine + GetProfitDistanceSlippage(position, bot.Securiti); bot.CloseAtProfit(position, priceRedLine, priceOrder); } } }
/// <summary> /// closing logic /// логика закрытия позиции /// </summary> private void Strateg_ClosePosition(Position position) { List <Position> openPositions = _tab.PositionsOpenAll; for (int i = 0; openPositions != null && i < openPositions.Count; i++) { if (openPositions[i].Direction == Side.Buy) { decimal heightPattern = Math.Abs(_tab.CandlesAll[_tab.CandlesAll.Count - 3].Open - _tab.CandlesAll[_tab.CandlesAll.Count - 1].Close); decimal priceStop = _lastPrice - (heightPattern * ProcHeightStop) / 100; decimal priceTake = _lastPrice + (heightPattern * ProcHeightTake) / 100; _tab.CloseAtStop(openPositions[i], priceStop, priceStop - Slipage); _tab.CloseAtProfit(openPositions[i], priceTake, priceTake - Slipage); } else { decimal heightPattern = Math.Abs(_tab.CandlesAll[_tab.CandlesAll.Count - 1].Close - _tab.CandlesAll[_tab.CandlesAll.Count - 3].Open); decimal priceStop = _lastPrice + (heightPattern * ProcHeightStop) / 100; decimal priceTake = _lastPrice - (heightPattern * ProcHeightTake) / 100; _tab.CloseAtStop(openPositions[i], priceStop, priceStop + Slipage); _tab.CloseAtProfit(openPositions[i], priceTake, priceTake + Slipage); } } }
private void Strateg_PositionOpen(Position position) { _tab.SellAtStopCancel(); _tab.BuyAtStopCancel(); decimal profit = Math.Abs((_lastPcUp - _lastPcDown)) * 1; List <Position> openPositions = _tab.PositionsOpenAll; for (int i = 0; openPositions != null && i < openPositions.Count; i++) { if (openPositions[i].Direction == Side.Buy) { _tab.SellAtStopCancel(); _tab.CloseAtStop(openPositions[i], _lastPcDown, _lastPcDown - Slipage.ValueDecimal); _tab.CloseAtProfit(openPositions[i], openPositions[i].EntryPrice + profit + Slipage.ValueDecimal, openPositions[i].EntryPrice + profit); } else { _tab.BuyAtStopCancel(); _tab.CloseAtStop(openPositions[i], _lastPcUp, _lastPcUp + Slipage.ValueDecimal); _tab.CloseAtProfit(openPositions[i], openPositions[i].EntryPrice - profit - Slipage.ValueDecimal, openPositions[i].EntryPrice - profit); } } }
void StopLoss() // фиксация убытков { List <Position> positions = _vkl.PositionsOpenAll; if (_vkl.MarketDepth.Asks[0].Price + Step(_kom / 2) < _vkl.PositionsLast.EntryPrice) // { Kol_Trad(); int аznach = Kol_Trad(); if (аznach == zn_stop_los) { _vkl.CloseAtStop(positions[0], _vkl.MarketDepth.Asks[0].Price, _vkl.MarketDepth.Asks[0].Price - Step(OtProfit + DeltaUsredn) - _kom / 2); Thread.Sleep(3000); Vkl = false; // после выставления стоплоса выключаем робот } } }
void StopLoss() // фиксация убытков { if (vkl_stopa.ValueBool == false) { return; } List <Position> positions = _tab.PositionsOpenAll; if (positions.Count != 0) { if (price > _tab.PositionsLast.EntryPrice + do_stopa.ValueDecimal) // когда рынок выше закупки позиции { Console.WriteLine("Вошли в условие выставление стопа " + (_tab.PositionsLast.EntryPrice + do_stopa.ValueDecimal)); _tab.CloseAtStop(positions[0], price, price); Console.WriteLine("Выставили СТОПлос по Активация " + price + " с ордером " + price); } } }
private void ClosePosLogic(List <Candle> candles, Position pos) { if (pos.State != PositionStateType.Open) { return; } if (pos.StopOrderIsActiv == true || pos.ProfitOrderIsActiv == true) { return; } decimal profitActivation = pos.EntryPrice + pos.EntryPrice * ProfitLenPercent.ValueDecimal / 100; _tab.CloseAtProfit(pos, profitActivation, profitActivation); decimal stopActivation = pos.EntryPrice - pos.EntryPrice * StopLenPercent.ValueDecimal / 100; _tab.CloseAtStop(pos, stopActivation, stopActivation); }
/// <summary> /// попробовать закрыть позицию /// </summary> private void TryClosePosition(Position position, List <Candle> candles) { if (EmulatorIsOn) { int currentEmuPos = GetCurrentPosition(); if (currentEmuPos == 0 || currentEmuPos == 1 && position.Direction == Side.Sell || currentEmuPos == -1 && position.Direction == Side.Buy) { _tab.SetNewLogMessage("Кроем позицию по эмулятору. Номер позиции: " + position.Number, LogMessageType.System); // Выход по эмулятору! позиции нет. Нужно закрывать полюбой цене _tab.CloseAllOrderToPosition(position); _timeToClose = DateTime.Now.AddSeconds(3); _positionToClose = position; return; } } // первый выход по проколу if (Shoulderette(candles.Count - 1, candles)) { // если произошёл прокол и мы заработали больше 20% if (position.EntryPrice * 1.2m <= candles[candles.Count - 1].Close) { _tab.CloseAtLimit(position, candles[candles.Count - 1].Close - SlipageCloseFirst * _tab.Securiti.PriceStep, position.OpenVolume); //Sell(_settings.Position, _myCandles[_myCandles.Length - 1].ClosePrice); return; } } // второй выход по стопам if (position.Direction == Side.Buy) { decimal priceEtalon = Math.Round(((Line)_chandelier).Values[((Line)_chandelier).Values.Count - 1], _tab.Securiti.Decimals); if (_tab.Securiti.Decimals == 0) { priceEtalon = Math.Truncate(((Line)_chandelier).Values[((Line)_chandelier).Values.Count - 1]); } decimal priceOrder = priceEtalon - _tab.Securiti.PriceStep * SlipageCloseFirst; // ЗДЕСЬ!!!!!!!!!!!!!! decimal priceRedLine = priceEtalon + _tab.Securiti.PriceStep * SlipageReversClose; if (priceRedLine - _tab.Securiti.PriceStep * 10 > _tab.PriceBestAsk) { _tab.CloseAtLimit(position, _tab.PriceBestAsk, position.OpenVolume); return; } _tab.CloseAtStop(position, priceRedLine, priceOrder); if (StartProgram != StartProgram.IsTester && AlertIsOn) { _alert.PriceActivation = priceRedLine + SlipageToAlert * _tab.Securiti.PriceStep; _alert.TypeActivation = PriceAlertTypeActivation.PriceLowerOrEqual; _alert.MessageIsOn = true; _alert.MusicType = AlertMusic.Duck; _alert.Message = "Приближаемся к точке выхода"; _alert.IsOn = true; } } }
/// <summary> /// Метод перевода позиции в безубыток при достижении мин. профита /// </summary> /// <param name="position">Позиция, которая проверяется на возможность перевода в безубыток</param> private void SetStopForBreakeven(Position position) { if (position.State != PositionStateType.Open) { return; } // цена активации стоп ордера decimal priceActivation; // цена стоп ордера decimal priceOrder; // Если профит позиции больше минимально заданного профита if (position.ProfitOperationPersent > Convert.ToDecimal(MinProfitOnStopBreakeven.ValueInt)) { // установка фиксированного стопа для позиции лонг if (position.Direction == Side.Buy) { // цена активации устанавливается на 10 проскальзываний выше цены открытия позиции priceActivation = position.EntryPrice + 10 * Slippage.ValueInt * _tab.Securiti.PriceStep; // если цена активации получилась больше или равна последней цене, то ничего не делаем if (priceActivation >= _lastPrice) { return; } // если у позиции уже установлена цена активации и она не меньше, чем priceActivation, // то ничего не делаем if (position.StopOrderRedLine > 0 && priceActivation <= position.StopOrderRedLine) { return; } // цена стоп ордера устанавливается ниже на 3 проскальзывания от цены активации priceOrder = priceActivation - 3 * Slippage.ValueInt * _tab.Securiti.PriceStep; _tab.CloseAtStop(position, priceActivation, priceOrder); } // установка фиксированного стопа для позиции шорт else if (position.Direction == Side.Sell) { // цена активации устанавливается на 10 проскальзывания ниже цены открытия позиции priceActivation = position.EntryPrice - 10 * Slippage.ValueInt * _tab.Securiti.PriceStep; // если цена активации получилась меньше или равна последней цене, то ничего не делаем if (priceActivation <= _lastPrice) { return; } // если у позиции уже установлена цена активации и она не меньше, чем priceActivation, // то ничего не делаем if (position.StopOrderRedLine > 0 && priceActivation >= position.StopOrderRedLine) { return; } // цена стоп ордера устанавливается выше на величину 3 проскальзываний от цены активации priceOrder = priceActivation + 3 * Slippage.ValueInt * _tab.Securiti.PriceStep; _tab.CloseAtStop(position, priceActivation, priceOrder); } } return; }
/// <summary> /// выставить стоп приказ по открытой позиции /// </summary> private void TryClosePosition(Position position, List <Candle> candles) { if (EmulatorIsOn) { int currentEmuPos = GetCurrentPosition(); if (currentEmuPos == 0 || currentEmuPos == 1 && position.Direction == Side.Sell || currentEmuPos == -1 && position.Direction == Side.Buy) { _tab.SetNewLogMessage("Кроем позицию по эмулятору. Номер позиции: " + position.Number, LogMessageType.System); // Выход по эмулятору! позиции нет. Нужно закрывать полюбой цене _tab.CloseAllOrderToPosition(position); _timeToClose = DateTime.Now.AddSeconds(3); _positionToClose = position; return; } } if (position.Direction == Side.Buy) { decimal priceEtalon = GetPriseStop(Side.Buy, candles.Count - 1); decimal priceOrder = priceEtalon - _tab.Securiti.PriceStep * SlipageCloseFirst; // ЗДЕСЬ!!!!!!!!!!!!!! decimal priceRedLine = priceEtalon + SlipageReversClose * _tab.Securiti.PriceStep; if (priceRedLine - _tab.Securiti.PriceStep * 10 > _tab.PriceBestAsk) { _tab.CloseAtLimit(position, _tab.PriceBestAsk, position.OpenVolume); return; } _tab.CloseAtStop(position, priceRedLine, priceOrder); if (StartProgram != StartProgram.IsTester && AlertIsOn) { _alert.PriceActivation = priceRedLine + SlipageToAlert * _tab.Securiti.PriceStep; _alert.TypeActivation = PriceAlertTypeActivation.PriceLowerOrEqual; _alert.MessageIsOn = true; _alert.MusicType = AlertMusic.Duck; _alert.Message = "Приближаемся к точке выхода"; _alert.IsOn = true; } } if (position.Direction == Side.Sell) { decimal priceEtalon = GetPriseStop(Side.Sell, candles.Count - 1); decimal priceOrder = priceEtalon + _tab.Securiti.PriceStep * SlipageCloseFirst; // ЗДЕСЬ!!!!!!!!!!!!!! decimal priceRedLine = priceEtalon - SlipageReversClose * _tab.Securiti.PriceStep; if (priceRedLine + _tab.Securiti.PriceStep * 10 < _tab.PriceBestAsk) { _tab.CloseAtLimit(position, _tab.PriceBestAsk, position.OpenVolume); return; } _tab.CloseAtStop(position, priceRedLine, priceOrder); if (StartProgram != StartProgram.IsTester && AlertIsOn) { _alert.PriceActivation = priceRedLine - SlipageToAlert * _tab.Securiti.PriceStep; _alert.TypeActivation = PriceAlertTypeActivation.PriceHigherOrEqual; _alert.MessageIsOn = true; _alert.MusicType = AlertMusic.Duck; _alert.Message = "Приближаемся к точке выхода"; _alert.IsOn = true; } } }
/// <summary> /// проверить условия на закрытие позиции /// </summary> private void TryClosePosition(Position position) { if (EmulatorIsOn) { int currentEmuPos = GetCurrentPosition(); if (currentEmuPos == 0 || currentEmuPos == 1 && position.Direction == Side.Sell || currentEmuPos == -1 && position.Direction == Side.Buy) { // Выход по эмулятору! позиции нет. Нужно закрывать полюбой цене _tab.CloseAllOrderToPosition(position); _timeToClose = DateTime.Now.AddSeconds(3); _positionToClose = position; return; } } // БАЙ if (position.Direction == Side.Sell) { decimal lineBuy = GetPriceToClosePos(Side.Buy); if (lineBuy == 0) { return; } decimal priceOrder = lineBuy + _tab.Securiti.PriceStep * SlipageCloseFirst; // ЗДЕСЬ!!!!!!!!!!!!!! decimal priceRedLine = lineBuy - _tab.Securiti.PriceStep * SlipageReversClose; if (priceRedLine + _tab.Securiti.PriceStep * 10 < _tab.PriceBestAsk) { _tab.CloseAtLimit(position, _tab.PriceBestAsk, position.OpenVolume); return; } _tab.CloseAtStop(position, priceRedLine, priceOrder); } // СЕЛЛ if (position.Direction == Side.Buy) { decimal lineSell = GetPriceToClosePos(Side.Sell); if (lineSell == 0) { return; } decimal priceOrderSell = lineSell - _tab.Securiti.PriceStep * SlipageCloseFirst; // ЗДЕСЬ!!!!!!!!!!!!!! decimal priceRedLineSell = lineSell + _tab.Securiti.PriceStep * SlipageReversClose; if (priceRedLineSell - _tab.Securiti.PriceStep * 10 > _tab.PriceBestAsk) { _tab.CloseAtLimit(position, _tab.PriceBestAsk, position.OpenVolume); return; } _tab.CloseAtStop(position, priceRedLineSell, priceOrderSell); } }
decimal all_volum_trade_min; //все объемы за N минуту private void _vklad_NewTickEvent(Trade trade) // событие новых тиков для счета объема торгов { price = _vklad.PriceCenterMarketDepth; // записываем текущую цену рынка if (vkl_vol_trade.ValueBool == false) { return; } List <Position> positions = _vklad.PositionsOpenAll; DateTime time_add_n_min; time_add_n_min = dateTrade.AddMinutes(n_min.ValueInt); if (trade.Time < time_add_n_min) { if (trade.Side == Side.Buy) { decimal b = trade.Volume; bid_vol_tr = bid_vol_tr + b; } if (trade.Side == Side.Sell) { decimal a = trade.Volume; ask_vol_tr = ask_vol_tr + a; } all_volum_trade_min = bid_vol_tr + ask_vol_tr; } else { dateTrade = trade.Time; all_volum_trade_min = 0; bid_vol_tr = 0; ask_vol_tr = 0; } if (bid_vol_tr > volum_piramid.ValueInt) { Price_kon_trade(); if (volum_ma > Price_kon_trade() && positions.Count > 0) { if (piramid_stop == false) { return; } _vklad.BuyAtMarketToPosition(positions[0], Okreglenie(VolumForUsred())); Kol_Trad(); Mnog(); Console.WriteLine("Докупились при объеме покупок больше " + volum_piramid.ValueInt + " по- " + Price_kon_trade() + "НА " + VolumForUsred() * _vklad.PriceBestAsk); piramid_stop = false; bid_vol_tr = 0; } } if (ask_vol_tr > volum_alarm.ValueInt && positions.Count > 0) // условие для аварийного выключения { if (alarm == false) { return; } slippage.ValueDecimal = slippage.ValueDecimal + 1m; _vklad.CloseAtStop(positions[0], _vklad.MarketDepth.Asks[0].Price, _vklad.MarketDepth.Asks[0].Price - slippage.ValueDecimal); vkl_Robota.ValueBool = false; // после выставления стопа выключаем робот Console.WriteLine(" Аварийное выключение!!! ОБЪЕМЫ продаж больше " + volum_alarm.ValueInt + " РОБОТ ВЫКЛЮЧЕН по цене - " + Price_kon_trade()); slippage.ValueDecimal = slippage.ValueDecimal - 1m; Console.WriteLine("Вернули проскальзыванию начальное значение - " + slippage.ValueDecimal); if (positions.Count == 0) { alarm = false; bid_vol_tr = 0; } } }