private void TradeLogic(List <Candle> candles) { if (candles.Count < 5) { return; } // если уже есть открытые позиции - закрываем и выходим if (_tab.PositionsOpenAll != null && _tab.PositionsOpenAll.Count != 0) { _tab.CloseAllAtMarket(); return; } // если закрытие последней свечи выше закрытия предыд - покупаем if (candles[candles.Count - 1].Close > candles[candles.Count - 2].Close) { _tab.BuyAtMarket(1); } // если закрытие последней свечи ниже закрытия предыд - продаем if (candles[candles.Count - 1].Close < candles[candles.Count - 2].Close) { _tab.SellAtMarket(1); } }
private void LogicOpenPosition(List <Candle> candles, List <Position> position) { if (candles[candles.Count - 1].TimeStart.Month != 3 && candles[candles.Count - 1].TimeStart.Month != 6 && candles[candles.Count - 1].TimeStart.Month != 9 && candles[candles.Count - 1].TimeStart.Month != 12) { return; } if (candles[candles.Count - 1].TimeStart.Day < 30 - DaysBeforeEndQuarterToInter.ValueInt) { return; } if (FBD.DataSeries[0].Last > IndicatorDivergence.ValueDecimal) { decimal volume = _tab.Portfolio.ValueCurrent / candles[candles.Count - 1].Close; _tab.SellAtMarket(volume, candles[candles.Count - 1].TimeStart.AddDays(DaysInPosition.ValueInt).ToString()); } if (FBD.DataSeries[0].Last < -IndicatorDivergence.ValueDecimal) { decimal volume = _tab.Portfolio.ValueCurrent / candles[candles.Count - 1].Close; _tab.BuyAtMarket(volume, candles[candles.Count - 1].TimeStart.AddDays(DaysInPosition.ValueInt).ToString()); } }
/// <summary> /// open position logic /// логика открытия позиции /// </summary> private void LogicOpenPosition(List <Candle> candles, List <Position> position) { List <Position> openPositions = _tab.PositionsOpenAll; if (openPositions == null || openPositions.Count == 0) { // long if (Regime.ValueString != "OnlyShort") { if (_lastPrice > _lastPcUp) { // _tab.BuyAtLimit(Volume.ValueDecimal, _lastPrice + Slippage.ValueInt * _tab.Securiti.PriceStep); _tab.BuyAtMarket(Volume.ValueDecimal); } } // Short if (Regime.ValueString != "OnlyLong") { if (_lastPrice < _lastPcDown) { // _tab.SellAtLimit(Volume.ValueDecimal, _lastPrice - Slippage.ValueInt * _tab.Securiti.PriceStep); _tab.SellAtMarket(Volume.ValueDecimal); } } } }
/// <summary> /// trade logic /// </summary> private void Trade() { if (_candles1.Count < 20 && _candles2.Count < 20) { return;; } if (Regime.ValueString == "Off") { return; } List <Position> pos1 = _tab1.PositionsOpenAll; List <Position> pos2 = _tab2.PositionsOpenAll; if (pos1 != null && pos1.Count != 0 || pos2 != null && pos2.Count != 0) { return; } if (_rsi1.DataSeries[0].Values == null || _rsi2.DataSeries[0].Values == null) { return; } if (_rsi1.DataSeries[0].Values.Count < _rsi1.ParametersDigit[0].Value + 3 || _rsi2.DataSeries[0].Values.Count < _rsi2.ParametersDigit[0].Value + 3) { return; } decimal lastRsi1 = _rsi1.DataSeries[0].Values[_rsi1.DataSeries[0].Values.Count - 1]; decimal lastRsi2 = _rsi2.DataSeries[0].Values[_rsi2.DataSeries[0].Values.Count - 1]; if (lastRsi1 > lastRsi2 + RsiSpread.ValueDecimal) { _tab1.SellAtMarket(Volume1.ValueDecimal); _tab2.BuyAtMarket(Volume2.ValueDecimal); } if (lastRsi2 > lastRsi1 + RsiSpread.ValueDecimal) { _tab1.BuyAtMarket(Volume1.ValueDecimal); _tab2.SellAtMarket(Volume2.ValueDecimal); } }
/// <summary> /// Обработчик успешного открытия позиции по инструменту 2 /// </summary> /// <param name="position2">Успешно открытая позиция по инструменту 2</param> private void _tab2_PositionOpeningSuccesEvent(Position position2) { if (WhoIsFirst != WhoIsFirst.Second) { return; } // в зависимости от направления открытой позиции по инструменту 2 // выставляем противоположную рыночную заявку по инструменту 1 if (position2.Direction == Side.Sell) { _tab1.BuyAtMarket(Volume1); } else if (position2.Direction == Side.Buy) { _tab1.SellAtMarket(Volume1); } }
/// <summary> /// sell on the market, for active bot /// продать по маркету, для активного бота /// </summary> /// <param name="volume">volume / объём</param> public void BotSellMarket(decimal volume) { try { if (IsActiv()) { if (_activPanel.ActivTab.GetType().Name == "BotTabSimple") { BotTabSimple tab = (BotTabSimple)_activPanel.ActivTab; tab.SellAtMarket(volume); } } } catch (Exception error) { SendNewLogMessage(error.ToString(), LogMessageType.Error); } }
/// <summary> /// логика торговли /// </summary> /// <param name="candles"></param> private void LogicOpenPosition(List <Candle> candles) { if (_lines == null || _lines.Count == 0) { return; } // 1 выясняем каким объёмом и в какую сторону нам надо заходить decimal totalDeal = 0; decimal lastPrice = candles[candles.Count - 2].Close; decimal nowPrice = candles[candles.Count - 1].Close; for (int i = 0; i < _lines.Count; i++) { if (lastPrice < _lines[i] && nowPrice > _lines[i]) { // пробой снизу вверх totalDeal--; } if (lastPrice > _lines[i] && nowPrice < _lines[i]) { // пробой сверху вниз totalDeal++; } } if (totalDeal == 0) { return; } // 2 заходим в нужную сторону if (totalDeal > 0) { // нужно лонговать List <Position> positionsShort = _tab.PositionOpenShort; if (positionsShort != null && positionsShort.Count != 0) { if (positionsShort[0].OpenVolume <= totalDeal) { _tab.CloseAtMarket(positionsShort[0], positionsShort[0].OpenVolume); totalDeal -= positionsShort[0].OpenVolume; } else { _tab.CloseAtMarket(positionsShort[0], totalDeal); totalDeal = 0; } } if (totalDeal > 0 && totalDeal != 0) { List <Position> positionsLong = _tab.PositionOpenLong; if (positionsLong != null && positionsLong.Count != 0) { _tab.BuyAtMarketToPosition(positionsLong[0], totalDeal); } else { _tab.BuyAtMarket(totalDeal); } } } if (totalDeal < 0) { // нужно шортить totalDeal = Math.Abs(totalDeal); List <Position> positionsLong = _tab.PositionOpenLong; if (positionsLong != null && positionsLong.Count != 0) { if (positionsLong[0].OpenVolume <= totalDeal) { _tab.CloseAtMarket(positionsLong[0], positionsLong[0].OpenVolume); totalDeal -= positionsLong[0].OpenVolume; } else { _tab.CloseAtMarket(positionsLong[0], totalDeal); totalDeal = 0; } } if (totalDeal > 0) { List <Position> positionsShort = _tab.PositionOpenShort; if (positionsShort != null && positionsShort.Count != 0) { _tab.SellAtMarketToPosition(positionsShort[0], totalDeal); } else { _tab.SellAtMarket(totalDeal); } } } }
/// <summary> /// проверить условия на вход в позицию /// </summary> private void TryOpenPosition(List <Candle> candles) { decimal damping; decimal avgHigh2; decimal avgLow3; decimal avgLow2; decimal avgHigh3; decimal avgHighShifted; decimal avgLowShifted; try { if (((MovingAverage)_smaHigh4Period).Values.Count - 1 - 10 < 0) { return; } damping = ((Line)_dampIndex).Values[((Line)_dampIndex).Values.Count - 1]; avgHigh2 = ((MovingAverage)_smaHigh2Period).Values[((MovingAverage)_smaHigh2Period).Values.Count - 1]; // SMA.Series(High, 2); avgLow3 = ((MovingAverage)_smaLow3Period).Values[((MovingAverage)_smaLow3Period).Values.Count - 1]; //SMA.Series(Low, 3); avgLow2 = ((MovingAverage)_smaLow3Period).Values[((MovingAverage)_smaLow3Period).Values.Count - 1]; //SMA.Series(Low, 3); avgHigh3 = ((MovingAverage)_smaHigh3Period).Values[((MovingAverage)_smaHigh3Period).Values.Count - 1]; //SMA.Series(High, 3); avgHighShifted = ((MovingAverage)_smaHigh4Period).Values[((MovingAverage)_smaHigh4Period).Values.Count - 1 - 10]; //SMA.Series(High, 4) >> 10; avgLowShifted = ((MovingAverage)_smaLow4Period).Values[((MovingAverage)_smaLow4Period).Values.Count - 1 - 10]; //SMA.Series(Low, 4) >> 10; } catch (Exception error) { _tab.SetNewLogMessage(error.ToString(), LogMessageType.Error); return; } if (EmulatorIsOn) { int currentEmuPos = GetCurrentPosition(); if (currentEmuPos != 0) { return; } } if (damping < 1 && (candles[candles.Count - 1].Close > avgHigh2) && (avgLow3 > avgHighShifted)) { _tab.SetNewLogMessage("Системный вход в лонг. Время: " + candles[candles.Count - 1].TimeStart, LogMessageType.Signal); if (StartProgram == StartProgram.IsTester) { _tab.BuyAtMarket(Volume); } else { _tab.BuyAtLimit(Volume, candles[candles.Count - 1].Close + _tab.Securiti.PriceStep * SlipageOpenFirst); // ЗДЕСЬ!!!!!!!!!!!!!! } return; } else if (damping < 1 && (candles[candles.Count - 1].Close < avgLow2) && (avgHigh3 < avgLowShifted)) { _tab.SetNewLogMessage("Системный вход в шорт. Время: " + candles[candles.Count - 1].TimeStart, LogMessageType.Signal); if (StartProgram == StartProgram.IsTester) { _tab.SellAtMarket(Volume); } else { _tab.SellAtLimit(Volume, candles[candles.Count - 1].Close - _tab.Securiti.PriceStep * SlipageOpenFirst); // ЗДЕСЬ!!!!!!!!!!!!!! } return; } else if (damping <= 1) { if (AlertIsOn) { AlertMessageManager.ThrowAlert(Properties.Resources.Duck, NameStrategyUniq, "Внимание! DI меньше 1, но входа не произошло. На следующей свече возможно открытие"); } } }
/// <summary> /// trade logic / /// логика торговли /// </summary> /// <param name="candles"></param> private void LogicOpenPosition(List <Candle> candles) { if (_lines == null || _lines.Count == 0) { return; } // 1 find out how much and in what direction we need to go // 1 выясняем каким объёмом и в какую сторону нам надо заходить decimal totalDeal = 0; decimal lastPrice = candles[candles.Count - 2].Close; decimal nowPrice = candles[candles.Count - 1].Close; for (int i = 0; i < _lines.Count; i++) { if (lastPrice < _lines[i] && nowPrice > _lines[i]) { totalDeal--; } if (lastPrice > _lines[i] && nowPrice < _lines[i]) { totalDeal++; } } if (totalDeal == 0) { return; } // 2 go in the right direction // 2 заходим в нужную сторону if (totalDeal > 0) { List <Position> positionsShort = _tab.PositionOpenShort; if (positionsShort != null && positionsShort.Count != 0) { if (positionsShort[0].OpenVolume <= totalDeal) { _tab.CloseAtMarket(positionsShort[0], positionsShort[0].OpenVolume); totalDeal -= positionsShort[0].OpenVolume; } else { _tab.CloseAtMarket(positionsShort[0], totalDeal); totalDeal = 0; } } if (totalDeal > 0 && totalDeal != 0) { List <Position> positionsLong = _tab.PositionOpenLong; if (positionsLong != null && positionsLong.Count != 0) { _tab.BuyAtMarketToPosition(positionsLong[0], totalDeal); } else { _tab.BuyAtMarket(totalDeal); } } } if (totalDeal < 0) { totalDeal = Math.Abs(totalDeal); List <Position> positionsLong = _tab.PositionOpenLong; if (positionsLong != null && positionsLong.Count != 0) { if (positionsLong[0].OpenVolume <= totalDeal) { _tab.CloseAtMarket(positionsLong[0], positionsLong[0].OpenVolume); totalDeal -= positionsLong[0].OpenVolume; } else { _tab.CloseAtMarket(positionsLong[0], totalDeal); totalDeal = 0; } } if (totalDeal > 0) { List <Position> positionsShort = _tab.PositionOpenShort; if (positionsShort != null && positionsShort.Count != 0) { _tab.SellAtMarketToPosition(positionsShort[0], totalDeal); } else { _tab.SellAtMarket(totalDeal); } } } }
private void _tab_MarketDepthUpdateEvent(MarketDepth marketDepth) // начало торгов { List <Position> positions = _tab.PositionsOpenAll; if (positions.Count != 0) { if (price > _tab.PositionsLast.EntryPrice) { StopLoss(); } } decimal priceOrder = price + profit.ValueInt + slippage.ValueDecimal * _tab.Securiti.PriceStep; decimal priceActivation = price + profit.ValueInt; if (positions.Count != 0) { if (price < _tab.PositionsLast.EntryPrice - profit.ValueInt - _kom - slippage.ValueDecimal) { _tab.CloseAtTrailingStop(positions[0], priceActivation, priceOrder); Console.WriteLine(" Включился Трейлинг Профит по - " + priceActivation); } } if (vkl_Robota.ValueBool == false) { return; } Percent_birgi(); Balans_tovara(); if (price < _uroven.ValueDecimal) { decimal vol = tovar / part_tovara.ValueInt; if (_tab.PositionsOpenAll.Count == 0) { if (vol > Lot() + min_lot.ValueDecimal / 4) { //объем входа- >> _tab.SellAtMarket(Okruglenie(vol - min_lot.ValueDecimal / 4)); Console.WriteLine(" начали продавать часть товара) по цене " + price + " На объем " + (vol - min_lot.ValueDecimal / 4) * price); Thread.Sleep(1500); } } if (positions.Count != 0) { if (price < _tab.PositionsLast.EntryPrice - _kom - do_piram.ValueDecimal) { Piramid(); } } } if (_tab.PositionsOpenAll.Count == 0) // сдвиг уровня работы { if (price > _uroven.ValueDecimal) // цена выше уровня работы + величина движения + комиссия { decimal r = price - _uroven.ValueDecimal; // вычисляем разницу (на сколько изменилась цена) if (r > dvig.ValueInt) { _uroven.ValueDecimal = _uroven.ValueDecimal + (r - ot_rinka.ValueInt); Console.WriteLine(" Позиций нет, уровень срабатывания поднимаем, теперь " + _uroven.ValueDecimal); } } } }
private void OpenPosition(Side side, decimal price, string Signal) { Slipage = _Slipage.ValueInt * _tab.Securiti.PriceStep; decimal _Vol; LastStop = GetStopLevel(side, price); // LastStop = GetStopByPattern(side, price, Signal); if (LastStop == 0) { return; } decimal VollAll = leverage.ValueInt * (_tab.Portfolio.ValueCurrent - _tab.Portfolio.ValueBlocked) / GetPrice(price); decimal StopSize = Math.Abs((LastStop - price) / price); if (StopSize <= 0) { return; } _Vol = (MaxStop.ValueDecimal / 100) * VollAll / (StopSize); // нужно разбираться почему так происходит if (_Vol > VollAll) { _Vol = VollAll; } _Vol = GetVol(_Vol); LastPositionVolume_All = _Vol; if (_Vol > 0) { if (StepCount.ValueInt > 1 && ((side == Side.Buy && price > (_TradeSessions.MinSessionPrice + _TradeSessions.MaxSessionPrice) / 2) || (side == Side.Sell && price < (_TradeSessions.MinSessionPrice + _TradeSessions.MaxSessionPrice) / 2))) { decimal v = GetVol(_Vol / GetPieceCount()); if (v == 0 && _Vol > 0) { v = 1; } if (side == Side.Buy) { _tab.BuyAtMarket(v, Signal); } else { _tab.SellAtMarket(v, Signal); } NeadStepOpen = true; } else { if (side == Side.Buy) { _tab.BuyAtMarket(_Vol, Signal); } else { _tab.SellAtMarket(_Vol, Signal); } } } }