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); } } } }
private void _vkl_MarketDepthUpdateEvent(MarketDepth marketDepth) // начинается работа с этого метода { if (count < _machka.Lenght) { return; } List <Position> positions = _vkl.PositionsOpenAll; volum_ma = _machka.Values[_machka.Values.Count - 1]; Percent_birgi(); // расчет величины в пунктах процента биржи if (_vkl.PositionsOpenAll.Count != 0) // { if (_vkl.MarketDepth.Bids[0].Price > _vkl.PositionsLast.EntryPrice) // цена выше закупки профитимся { Save_prifit(); Piramida(); } if (_vkl.MarketDepth.Asks[0].Price < _vkl.PositionsLast.EntryPrice) //цена ниже закупки усредняемся { Usrednenie(); StopLoss(); } } if (Vkl == false) // выключение работает как закрытие открытой позиции //с наименьшим убытком (проценты биржи) и не дает возможности открыть новую { if (_vkl.PositionsOpenAll.Count != 0) { if (_vkl.MarketDepth.Bids[0].Price > _vkl.PositionsLast.EntryPrice) { if (_vkl.PositionsLast.ProfitPortfolioPunkt > 0.1m) { _vkl.CloseAllAtMarket(); } } Thread.Sleep(5000); } return; } if (_vkl.PositionsOpenAll.Count == 0) // если не в рынке, открываемся по рынку { if (volum_ma < _vkl.MarketDepth.Asks[0].Price) // если цена выше уровня машки { if (last_hi_candl < _vkl.MarketDepth.Asks[0].Price) // если цена выше последнего хая { _mnog = 1; // начальная инициализация для вычисления количества входов Piramida dola_depa = old_vol_dv; //при отсутствие позиции присваивается значение взятое при старте оса (из файла) ZaprosBalahca(); Rac4et_baz_bal(); if (tek_bal_potfela / dola_depa > 10.1m) { _vkl.BuyAtMarket(Okreglenie(Depo / dola_depa)); Kol_Trad(); _vkl_PositionNetVolumeChangeEvent(positions[0]); } } } } }
/// <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); } }
private void _vklad_MarketDepthUpdateEvent(MarketDepth marketDepth) // логика работы запускается тут { if (_vklad.PositionsOpenAll.Count != 0) // { if (_vklad.MarketDepth.Bids[0].Price > _vklad.PositionsLast.EntryPrice) // цена выше закупки профитимся { Save_prifit(); // забрать профит } if (vkl_Robota.ValueBool == false) { StopLoss(); // фиксировать убыток } } if (vkl_Robota.ValueBool == false) // выключаем работу робота { return; } if (_vklad.PositionsOpenAll.Count != 0) { if (_vklad.MarketDepth.Asks[0].Price < _vklad.PositionsLast.EntryPrice) //цена ниже закупки усредняемся { Usrednenie(); StopLoss(); // фиксировать убыток } } if (volum_ma > 0) { if (_vklad.PositionsOpenAll.Count == 0) // если не в рынке, открываемся по рынку { if (volum_ma < _vklad.MarketDepth.Asks[0].Price) // если цена выше уровня машки { if (last_hi_candl < _vklad.MarketDepth.Asks[0].Price) // если цена выше последнего хая { Lot(); ZaprosBalahca(); Rac4et_baz_bal(); if (tek_bal_potfela / dola_depa.ValueInt > min_lot.ValueDecimal * price) { _vklad.BuyAtMarket(Okreglenie(Depo / dola_depa.ValueInt)); Console.WriteLine("Открылись по цене" + _vklad.PriceBestAsk + " НА - " + (Depo / dola_depa.ValueInt) * _vklad.PriceBestAsk + " $"); } } } } } }
/// <summary> /// buy on the market, for active bot /// купить по маркету, для активного бота /// </summary> /// <param name="volume">volume / объём</param> public void BotBuyMarket(decimal volume) { try { if (IsActiv()) { if (_activPanel.ActivTab.GetType().Name == "BotTabSimple") { BotTabSimple tab = (BotTabSimple)_activPanel.ActivTab; tab.BuyAtMarket(volume); } } } catch (Exception error) { SendNewLogMessage(error.ToString(), LogMessageType.Error); } }
private void OpenPosLogic(List <Candle> candles) { decimal lastFastSma = _fastSma.DataSeries[0].Last; decimal lastSlowSma = _slowSma.DataSeries[0].Last; if (lastFastSma < lastSlowSma) { return; } decimal lastAtr = _atr.DataSeries[0].Last; decimal len = lastFastSma - lastSlowSma; decimal lenCount = len / lastAtr; if (lenCount < AtrCountToInter.ValueDecimal) { return; } _tab.BuyAtMarket(Volume.ValueDecimal); }
/// <summary> /// logic open position /// логика открытия первой позиции /// </summary> private void LogicOpenPosition(List <Candle> candles, List <Position> position) { //if (_lastMacdDown < 0 && _lastMacdUp > _lastMacdDown // && Regime.ValueString != "OnlyShort") //{ // _tab.BuyAtLimit(Volume.ValueDecimal, _lastClose + Slippage.ValueInt * _tab.Securiti.PriceStep); //} // _tab.BuyAtAceberg() //if (_sma.DataSeries[0].Values == null || // _sma.ParametersDigit[0].Value + 3 > _sma.DataSeries[0].Values.Count) if (_TrixLow_min_pos == candles.Count && _TrixLow_min_period > _TrixLow.ParametersDigit[0].Value * 3 && _TrixLow_max_period > _TrixLow.ParametersDigit[0].Value * 3 && Regime.ValueString != "OnlyLong") { _Trix_seek_Hi = true; //_tab.BuyAtLimit(Volume.ValueDecimal, _lastClose + Slippage.ValueInt * _tab.Securiti.PriceStep); } else if (_Trix_seek_Hi && _TrixHi_min_pos == candles.Count && Regime.ValueString != "OnlyLong") { _Trix_seek_Hi = false; //_tab.BuyAtLimit(Volume.ValueDecimal, _lastClose + Slippage.ValueInt * _tab.Securiti.PriceStep); _tab.BuyAtMarket(Volume.ValueDecimal); _lastCandle = candles[candles.Count - 1]; } //if (_lastRsiD > 60 && _lastRsiK <= _lastRsiD && _prevRsiD < _prevRsiK // && Regime.ValueString != "OnlyLong") //{ // //_tab.SellAtLimit(Volume.ValueDecimal, _lastClose - Slippage.ValueInt * _tab.Securiti.PriceStep); // _tab.SellAtMarket(Volume.ValueDecimal); //} }
/// <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 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); } } } }