Exemple #1
0
 public void Create(TakeProfitOrderTest item)
 {
     takeProfitOrders.Add(item);
 }
Exemple #2
0
        private void CurrentTrades_LastPriceEvent(double lastPrice)
        {
            if (IsActiveAlgoritm)
            {
                //logService.Write("------------------CurrentTrades_LastPriceEvent------------------");
                //logService.Write($"currentPair.Pair: {simbol} lastPrice: {lastPrice} IsActiveAlgoritm: {IsActiveAlgoritm} Strategy: {tradeConfiguration.Strategy}");

                if (tradeConfiguration.Strategy == LONG_STRATEGY)
                {
                    // отслеживание OrderReload
                    var maxPrice = 0d;
                    try
                    {
                        maxPrice = stopLimitOrderRepository.MaxStopPriceBuy;
                    }
                    catch (Exception ex)
                    {
                        logService.Write($"maxPrice: error - {ex.Message}");
                        EndTask();
                        return;
                    }
                    //logService.Write($"maxPrice: {maxPrice}");

                    var indent = 0.0;
                    if (maxPrice > 0)
                    {
                        indent = ((lastPrice - maxPrice) * 100) / maxPrice;
                    }
                    //logService.Write($"indent: {indent} tradeConfiguration.OrderReload: {tradeConfiguration.OrderReload} isReload: {isReload}");

                    if (indent > tradeConfiguration.OrderReload && tradeConfiguration.OrderReload > 0 && isReload)
                    {
                        stopLimitOrderRepository.DeactivationAllOrders();
                        takeProfitOrderRepository.DeactivationAllOrders();
                        StartAlgoritm(lastPrice);

                        logService.Write($"Перемещение сетки OrderReload. indent: {indent} tradeConfiguration.OrderReload: {tradeConfiguration.OrderReload} isReload: {isReload}");
                        EndTask();
                        return;
                    }

                    // отслеживание исполнения стопов
                    //logService.Write("---- отслеживание исполнения стопов");
                    var stopOrders = stopLimitOrderRepository.GetActive(simbol).OrderByDescending(x => x.StopPrice);

                    foreach (var stopOrder in stopOrders)
                    {
                        //OnMessageDebugEvent("отслеживание исполнения стопов");
                        try
                        {
                            //logService.Write($"lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                            if (lastPrice <= stopOrder.StopPrice)
                            {
                                // get secret key
                                var publicKey = PUBLIC_KEY;
                                var secretKey = SECRET_KEY;

                                if (stopOrder.IsBuyOperation)
                                {
                                    logService.Write($"Сработал стоп на открытие позиции: stopOrder.Pair: {stopOrder.Pair} stopOrder.IsBuyOperation: {stopOrder.IsBuyOperation} stopOrder.Amount: {stopOrder.Amount} ** lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                                    isReload = false; // если есть иполнение запрещаем перестановку ордеров

                                    // обновляем стоп
                                    stopLimitOrderRepository.DeactivateOrder(stopOrder.ID);
                                    // выставляеим на Бинансе
                                    var position = positionRepository.GetOpen().FirstOrDefault();
                                    if (position != null)
                                    {
                                        position.IcreasePosition(stopOrder.Amount, lastPrice);
                                    }
                                    else
                                    {
                                        position = positionRepository.Create(new Position(stopOrder.Pair, stopOrder.Amount, lastPrice, isLong: true));
                                    }

                                    // снимаем все стопы-loss и профиты
                                    stopLimitOrderRepository.DeactivationAllOrders(publicKey, false);
                                    takeProfitOrderRepository.DeactivationAllOrders(publicKey);

                                    // выставляем профит
                                    var profitStop = new TakeProfitOrderTest()
                                    {
                                        FK_PublicKey     = publicKey,
                                        Pair             = stopOrder.Pair,
                                        StopPrice        = RoundAsset(position.Price + (position.Price * tradeConfiguration.Profit / 100)),
                                        IndentExtremum   = tradeConfiguration.IndentExtremum,
                                        ProtectiveSpread = tradeConfiguration.ProtectiveSpread,
                                        Amount           = RoundLotSize(Math.Abs(position.Amount)),
                                        IsBuyOperation   = false,
                                        Active           = true
                                    };
                                    takeProfitOrderRepository.Create(profitStop);
                                    logService.Write("выставляем профит");
                                    logService.Write($"Pair: {profitStop.Pair} StopPrice: {profitStop.StopPrice} IndentExtremum: {profitStop.IndentExtremum} ProtectiveSpread: {profitStop.ProtectiveSpread} Amount: {profitStop.Amount} IsBuyOperation: {profitStop.IsBuyOperation} Active: {profitStop.Active}");

                                    // выставляем лосс
                                    var lossStop = new StopLimitOrderTest()
                                    {
                                        FK_PublicKey   = publicKey,
                                        Pair           = stopOrder.Pair,
                                        StopPrice      = RoundAsset(position.Price - (position.Price * tradeConfiguration.Loss / 100)),
                                        Price          = 0,
                                        Amount         = RoundLotSize(Math.Abs(position.Amount)),
                                        IsBuyOperation = false,
                                        Active         = true
                                    };
                                    stopLimitOrderRepository.Create(lossStop);
                                    logService.Write("выставляем лосс");
                                    logService.Write($"Pair: {lossStop.Pair} StopPrice: {lossStop.StopPrice} Price: {lossStop.Price} Amount: {lossStop.Amount} IsBuyOperation: {lossStop.IsBuyOperation} Active: {lossStop.Active}");
                                }
                                else // сработал стоп-лосс
                                {
                                    logService.Write($"Сработал стоп-лосс. stopOrder.Pair: {stopOrder.Pair} stopOrder.IsBuyOperation: {stopOrder.IsBuyOperation} stopOrder.Amount: {stopOrder.Amount} ** lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                                    // выставляеим на Бинансе
                                    var position = positionRepository.GetOpen().FirstOrDefault();
                                    if (position != null)
                                    {
                                        position.ClosePosition(lastPrice);
                                    }
                                    else
                                    {
                                        // error
                                    }
                                    // все снимаем
                                    stopLimitOrderRepository.DeactivationAllOrders(publicKey);
                                    takeProfitOrderRepository.DeactivationAllOrders(publicKey);
                                    // начинаем заново
                                    StartAlgoritm(lastPrice);
                                    EndTask();
                                    return;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            // TODO: loging
                            logService.Write($"System error: {ex.Message}");
                        }
                    }

                    // отслеживание тейк-профитов
                    //logService.Write($"---- отслеживание тейк-профитов");
                    var takeProfits = takeProfitOrderRepository.GetActive(simbol).OrderBy(x => x.StopPrice);

                    //logService.Write($"foreach (var order in takeProfits) I -----------------");
                    foreach (var order in takeProfits)
                    {
                        //OnMessageDebugEvent($"LP:{lastPrice} * SP:{order.StopPrice}");
                        //logService.Write($"lastPrice: {lastPrice} stopOrder.StopPrice: {order.StopPrice} order.ExtremumPrice: {order.ExtremumPrice}");
                        if (lastPrice >= order.StopPrice && order.ExtremumPrice <= 0)
                        {
                            // update ExtremumPrice
                            //logService.Write($"Initialize ExtremumPrice: {lastPrice}");
                            takeProfitOrderRepository.UpdateExtremumPrice(order.ID, lastPrice);
                        }
                    }
                    //logService.Write($"end I -----------------");

                    takeProfits = takeProfits.Where(x => x.ExtremumPrice > 0).OrderByDescending(x => x.ExtremumPrice);

                    //logService.Write($"foreach (var order in takeProfits) II -----------------");
                    foreach (var order in takeProfits)
                    {
                        // get secret key
                        var publicKey = PUBLIC_KEY;
                        var secretKey = SECRET_KEY;

                        var indentExtremum = ((order.ExtremumPrice - lastPrice) * 100) / order.ExtremumPrice;
                        //OnMessageDebugEvent($"IE:{indentExtremum} * OIE:{order.IndentExtremum}");
                        //logService.Write($"indentExtremum: {indentExtremum} order.IndentExtremum: {order.IndentExtremum}");

                        if (indentExtremum >= order.IndentExtremum)
                        {
                            logService.Write($"Сработал тейк-профит: Pair: {order.Pair} StopPrice: {order.StopPrice} IndentExtremum: {order.IndentExtremum} ProtectiveSpread: {order.ProtectiveSpread} Amount: {order.Amount} IsBuyOperation: {order.IsBuyOperation} Active: {order.Active} ** lastPrice: {lastPrice}");

                            // выставляеим на Бинансе
                            var position = positionRepository.GetOpen().FirstOrDefault();
                            if (position != null)
                            {
                                position.ClosePosition(lastPrice);
                            }
                            else
                            {
                                // error
                            }
                            // все снимаем
                            stopLimitOrderRepository.DeactivationAllOrders(publicKey);
                            takeProfitOrderRepository.DeactivationAllOrders(publicKey);
                            // начинаем заново
                            StartAlgoritm(lastPrice);
                            EndTask();
                            return;
                        }

                        //OnMessageDebugEvent($"LP:{lastPrice} * SP:{order.StopPrice}");
                        //logService.Write($"Update ExtremumPrice");
                        //logService.Write($"lastPrice: {lastPrice} order.ExtremumPrice: {order.ExtremumPrice}");
                        if (lastPrice > order.ExtremumPrice && order.ExtremumPrice > 0)
                        {
                            // update ExtremumPrice
                            takeProfitOrderRepository.UpdateExtremumPrice(order.ID, lastPrice);
                        }
                    }
                    //logService.Write($"end II -----------------");
                    //----
                }

                //-----------------------------------------
                //----------- SHORT -----------------------
                //-----------------------------------------

                else if (tradeConfiguration.Strategy == SHORT_STRATEGY)
                {
                    //OnMessageDebugEvent("LONG_STRATEGY");
                    // отслеживание OrderReload
                    var minPrice = 0d;
                    try
                    {
                        minPrice = stopLimitOrderRepository.MinStopPriceSell;
                    }
                    catch (Exception ex)
                    {
                        logService.Write($"minPrice: error - {ex.Message}");
                        EndTask();
                        return;
                    }
                    //logService.Write($"minPrice: {minPrice}");

                    var indent = 0.0;
                    if (minPrice > 0)
                    {
                        indent = ((minPrice - lastPrice) * 100) / minPrice;
                    }
                    //logService.Write($"indent: {indent} tradeConfiguration.OrderReload: {tradeConfiguration.OrderReload} isReload: {isReload}");

                    if (indent > tradeConfiguration.OrderReload && tradeConfiguration.OrderReload > 0 && isReload)
                    {
                        stopLimitOrderRepository.DeactivationAllOrders();
                        takeProfitOrderRepository.DeactivationAllOrders();
                        StartAlgoritm(lastPrice);

                        logService.Write($"Перемещение сетки OrderReload. indent: {indent} tradeConfiguration.OrderReload: {tradeConfiguration.OrderReload} isReload: {isReload}");
                        EndTask();
                        return;
                    }

                    // отслеживание исполнения стопов
                    //logService.Write("---- отслеживание исполнения стопов");
                    var stopOrders = stopLimitOrderRepository.GetActive(simbol).OrderBy(x => x.StopPrice);

                    foreach (var stopOrder in stopOrders)
                    {
                        //OnMessageDebugEvent("отслеживание исполнения стопов");
                        try
                        {
                            //logService.Write($"lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                            if (lastPrice >= stopOrder.StopPrice)
                            {
                                logService.Write($"lastPrice: {lastPrice}");
                                // get secret key
                                var publicKey = PUBLIC_KEY;
                                var secretKey = SECRET_KEY;

                                if (!stopOrder.IsBuyOperation)
                                {
                                    logService.Write($"Сработал стоп на открытие позиции: stopOrder.Pair: {stopOrder.Pair} stopOrder.IsBuyOperation: {stopOrder.IsBuyOperation} stopOrder.Amount: {stopOrder.Amount} ** lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                                    isReload = false; // если есть иполнение запрещаем перестановку ордеров

                                    // обновляем стоп
                                    stopLimitOrderRepository.DeactivateOrder(stopOrder.ID);
                                    // выставляеим на Бинансе
                                    var position = positionRepository.GetOpen().FirstOrDefault();
                                    if (position != null)
                                    {
                                        position.IcreasePosition(stopOrder.Amount, lastPrice);
                                    }
                                    else
                                    {
                                        position = positionRepository.Create(new Position(stopOrder.Pair, stopOrder.Amount, lastPrice, isLong: false));
                                    }
                                    // снимаем все стопы-loss и профиты
                                    stopLimitOrderRepository.DeactivationAllOrders(publicKey, !stopOrder.IsBuyOperation);
                                    takeProfitOrderRepository.DeactivationAllOrders(publicKey);

                                    // выставляем профит
                                    var profitStop = CreateTakeProfitOrder(publicKey, stopOrder.Pair, position.Price, position.Amount, isBuyer: true);
                                    takeProfitOrderRepository.Create(profitStop);
                                    logService.Write("выставляем профит");
                                    logService.Write($"Pair: {profitStop.Pair} StopPrice: {profitStop.StopPrice} IndentExtremum: {profitStop.IndentExtremum} ProtectiveSpread: {profitStop.ProtectiveSpread} Amount: {profitStop.Amount} IsBuyOperation: {profitStop.IsBuyOperation} Active: {profitStop.Active}");

                                    // выставляем лосс
                                    double stopPrice = GetStopLossPrice(position.Price, tradeConfiguration.Loss, !stopOrder.IsBuyOperation);
                                    var    lossStop  = CreateStopLimitOrder(publicKey, stopOrder.Pair, stopPrice, RoundLotSize(Math.Abs(position.Amount)), true);
                                    stopLimitOrderRepository.Create(lossStop);
                                    logService.Write("выставляем лосс");
                                    logService.Write($"Pair: {lossStop.Pair} StopPrice: {lossStop.StopPrice} Price: {lossStop.Price} Amount: {lossStop.Amount} IsBuyOperation: {lossStop.IsBuyOperation} Active: {lossStop.Active}");
                                }
                                else // сработал стоп-лосс
                                {
                                    logService.Write($"Сработал стоп-лосс. ** lastPrice: {lastPrice} stopOrder.StopPrice: {stopOrder.StopPrice}");
                                    // выставляеим на Бинансе
                                    var position = positionRepository.GetOpen().FirstOrDefault();
                                    if (position != null)
                                    {
                                        position.ClosePosition(lastPrice);
                                    }
                                    else
                                    {
                                        // error
                                    }
                                    // все снимаем
                                    stopLimitOrderRepository.DeactivationAllOrders(publicKey);
                                    takeProfitOrderRepository.DeactivationAllOrders(publicKey);
                                    // начинаем заново
                                    StartAlgoritm(lastPrice);
                                    EndTask();
                                    return;
                                }
                            }
                            else
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            // TODO: loging
                            logService.Write($"System error: {ex.Message}");
                        }
                    }

                    // отслеживание тейк-профитов
                    //logService.Write($"---- отслеживание тейк-профитов");
                    var takeProfits = takeProfitOrderRepository.GetActive(simbol).OrderByDescending(x => x.StopPrice);

                    //logService.Write($"foreach (var order in takeProfits) I -----------------");
                    foreach (var order in takeProfits)
                    {
                        //OnMessageDebugEvent($"LP:{lastPrice} * SP:{order.StopPrice}");
                        //logService.Write($"lastPrice: {lastPrice} stopOrder.StopPrice: {order.StopPrice} order.ExtremumPrice: {order.ExtremumPrice}");
                        if (lastPrice <= order.StopPrice && order.ExtremumPrice <= 0)
                        {
                            // update ExtremumPrice
                            //logService.Write($"Initialize ExtremumPrice: {lastPrice}");
                            takeProfitOrderRepository.UpdateExtremumPrice(order.ID, lastPrice);
                        }
                    }
                    //logService.Write($"end I -----------------");

                    takeProfits = takeProfits.Where(x => x.ExtremumPrice > 0).OrderBy(x => x.ExtremumPrice);

                    //logService.Write($"foreach (var order in takeProfits) II -----------------");
                    foreach (var order in takeProfits)
                    {
                        // get secret key
                        var publicKey = PUBLIC_KEY;
                        var secretKey = SECRET_KEY;

                        var indentExtremum = ((lastPrice - order.ExtremumPrice) * 100) / order.ExtremumPrice;
                        //OnMessageDebugEvent($"IE:{indentExtremum} * OIE:{order.IndentExtremum}");
                        //logService.Write($"indentExtremum: {indentExtremum} order.IndentExtremum: {order.IndentExtremum}");

                        if (indentExtremum >= order.IndentExtremum)
                        {
                            logService.Write($"Сработал тейк-профит: Pair: {order.Pair} StopPrice: {order.StopPrice} IndentExtremum: {order.IndentExtremum} ProtectiveSpread: {order.ProtectiveSpread} Amount: {order.Amount} IsBuyOperation: {order.IsBuyOperation} Active: {order.Active} ** lastPrice: {lastPrice}");

                            // выставляеим на Бинансе
                            var position = positionRepository.GetOpen().FirstOrDefault();
                            if (position != null)
                            {
                                position.ClosePosition(lastPrice);
                            }
                            else
                            {
                                // error
                            }
                            // все снимаем
                            stopLimitOrderRepository.DeactivationAllOrders(publicKey);
                            takeProfitOrderRepository.DeactivationAllOrders(publicKey);
                            // начинаем заново
                            StartAlgoritm(lastPrice);
                            EndTask();
                            return;
                        }

                        //OnMessageDebugEvent($"LP:{lastPrice} * SP:{order.StopPrice}");
                        //logService.Write($"Update ExtremumPrice");
                        //logService.Write($"lastPrice: {lastPrice} order.ExtremumPrice: {order.ExtremumPrice}");
                        if (lastPrice < order.ExtremumPrice && order.ExtremumPrice > 0)
                        {
                            // update ExtremumPrice
                            takeProfitOrderRepository.UpdateExtremumPrice(order.ID, lastPrice);
                        }
                    }
                    //logService.Write($"end II -----------------");
                    //----
                }
                EndTask();
            }
        }