protected TradeAction EvalStopLoss(CMarket market, TradeAction result)
        {
            if (MainConfiguration.Configuration.EnableStopLoss)
            {
                //var now = market.CandleMaker.CurrentCandleDate;
                //var candleLen = MainConfiguration.Configuration.CandleWidthInSeconds / 60;
                //var E = Evaluations.EvaluationManager.Instance;

                if (Math.Abs(market.TotCoins) < 0.01M)
                {
                    // sono a zero
                    StopLoss.Reset();
                }
                else
                if (StopLoss.IsSell(this.CoinValue))
                {
                    var currentTrend = Trend();
                    if (currentTrend == TechnicalAnalysis.Trend.Fall)
                    {
                        StopLoss.Reset();
                        StopLoss.SellCounter++;
                        //AnalyticsTools.Call("stoploss");
                        //E.Add("stoploss", new Prediction() { Date = now, Type = PredictionType.LessThan, Value = this.CoinValue }, candleLen);
                        return(TradeAction.StrongSell);
                    }
                }
            }
            return(result); //TradeAction.Unknown;
        }
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            if (CurrentBar <= BarsRequired)
            {
                return;
            }

            _macd = MACD_ZeroLag_Colors(1, MACDFast, MACDSlow, MACDSmooth, 0);
            _rsi  = RSI(RSIPeriod, RSISmooth);

            // P(_macd.MacdUp + " " + _macd.MacdDn);
            if (IsFlat)
            {
                LookForEntry();
            }
            else
            {
                LookForStop();
                LookForExit();
            }



            if (!IsFlat)
            {
                ManageTradeByTrailingATR();
                PositionPrice.Set(_positionPrice);
                StopLoss.Set(_lossLevel);
            }
        }
        protected void ManageTradeByTrailingATR()
        {
            double risk = EMA(ATR(MMAtrPeriod), MMAtrEMAPeriod)[0] * MMAtrMultiplier;

            if (IsLong)
            {
                switch (_tradeState)
                {
                case TradeState.InitialStop:
                    // switch to breakeven if possible and start trailing
                    if (Close[0] > _positionPrice + (TickSize * ProfitTicksBeforeBreakeven))
                    {
                        _lossLevel = _positionPrice + (TickSize * BreakevenTicks);
                        StopLoss.Set(_lossLevel);
                        //    SetStopLoss("long", CalculationMode.Price, _lossLevel, true);
                        _tradeState = TradeState.Trailing;
                    }
                    break;

                case TradeState.Trailing:
                    if (Low[0] - risk > _lossLevel)
                    {
                        _lossLevel = Low[0] - risk;
                        StopLoss.Set(_lossLevel);
                        //       SetStopLoss("long", CalculationMode.Price, _lossLevel, true);
                    }
                    break;
                }
            }
            else if (IsShort)
            {
                switch (_tradeState)
                {
                case TradeState.InitialStop:
                    // switch to breakeven if possible and start trailing
                    if (Close[0] < _positionPrice - (TickSize * ProfitTicksBeforeBreakeven))
                    {
                        _lossLevel = _positionPrice - (TickSize * BreakevenTicks);
                        StopLoss.Set(_lossLevel);
                        //         SetStopLoss("short", CalculationMode.Price, _lossLevel, true);
                        _tradeState = TradeState.Trailing;
                    }
                    break;

                case TradeState.Trailing:
                    if (High[0] + risk < _lossLevel)
                    {
                        _lossLevel = High[0] + risk;
                        StopLoss.Set(_lossLevel);
                        //              SetStopLoss("short", CalculationMode.Price, _lossLevel, true);
                    }
                    break;
                }
            }
            StopLoss.Set(_lossLevel);
        }
        public string ToHtmlString()
        {
            StringBuilder b = new StringBuilder();

            b.Append("mark:        <b>" + Mark + "</b><br>");
            b.Append("amount:      <b>" + OpenAmount.ToString("0.########") + "</b><br>");
            b.Append("open price:  <b>" + OpenValue.ToString("0.########") + "</b><br>");
            b.Append("close price: <b>" + CloseValue.ToString("0.########") + "</b><br>");
            b.Append("stoploss:    <b>" + StopLoss.ToString("0.########") + "</b><br>");
            b.Append("change:      <b>" + Change.ToString("0.##") + "%</b><br>");
            b.Append("spent:       <b>" + Spent.ToString("0.########") + "</b><br>");
            b.Append("earned:      <b>" + Earned.ToString("0.########") + "</b><br>");
            b.Append("profit:      <b>" + Profit.ToString("0.########") + "</b><br>");
            return(b.ToString());
        }
        public async Task ExecuteStopLoss(StopLoss stopLoss)
        {
            if (!stopLoss.virtualSL)
            {
                var lowestRate = minimumTradeSatoshis / stopLoss.Quantity;
                LimitOrderResponse orderResp = await BtrexREST.PlaceLimitOrder(stopLoss.MarketDelta, "sell", stopLoss.Quantity, lowestRate);

                if (!orderResp.success)
                {
                    Trace.WriteLine(string.Format("    !!!!ERR ExecuteStopLoss-PLACE-ORDER1>> " + orderResp.message));
                    Trace.WriteLine(string.Format("        QTY: {1} ... STOP-LOSS RATE: {2}", stopLoss.Quantity, stopLoss.StopRate));

                    //REDUNTANT (FAILSAFE) CALL ON INITIAL CALL FAILURE
                    orderResp = await BtrexREST.PlaceLimitOrder(stopLoss.MarketDelta, "sell", stopLoss.Quantity, lowestRate);

                    if (!orderResp.success)
                    {
                        Trace.WriteLine("    !!!!ERR ExecuteStopLoss-PLACE-ORDER1.2ndTry>> " + orderResp.message);
                        Trace.WriteLine(string.Format("        QTY: {1} ... STOP-LOSS RATE: {2}", stopLoss.Quantity, stopLoss.StopRate));
                        return;
                    }
                }

                Thread.Sleep(1500);

                var order = await BtrexREST.GetOrder(orderResp.result.uuid);

                if (!order.success)
                {
                    Trace.WriteLine("    !!!!ERR ExecuteStopLoss-GET-ORDER: " + order.message);
                }

                stopLoss.ExecutionCallback(order.result, stopLoss.CandlePeriod);
            }
            else
            {
                var vSell = new GetOrderResult()
                {
                    Exchange     = stopLoss.MarketDelta,
                    Quantity     = stopLoss.Quantity,
                    PricePerUnit = BtrexData.Markets[stopLoss.MarketDelta].TradeHistory.RecentFills.Last().Rate * 0.9975M,
                    Closed       = DateTime.UtcNow
                };

                stopLoss.ExecutionCallback(vSell, stopLoss.CandlePeriod);
            }
        }
Beispiel #6
0
        public List <KeyValuePair <string, string> > ConverToKeyValue()
        {
            List <KeyValuePair <string, string> > keyValueData = new List <KeyValuePair <string, string> >();

            keyValueData.Add(new KeyValuePair <string, string>("Id", Id.ToString()));
            //keyValueData.Add(new KeyValuePair<string, string>("Number", Number.ToString()));
            keyValueData.Add(new KeyValuePair <string, string>("Code", Code));
            keyValueData.Add(new KeyValuePair <string, string>("OrderOperation", ((byte)OrderOperation).ToString()));
            keyValueData.Add(new KeyValuePair <string, string>("Account", Account));
            keyValueData.Add(new KeyValuePair <string, string>("Price", Price.ToString(System.Globalization.CultureInfo.InvariantCulture)));
            keyValueData.Add(new KeyValuePair <string, string>("Count", Count.ToString()));
            keyValueData.Add(new KeyValuePair <string, string>("Volume", Volume.ToString()));
            //keyValueData.Add(new KeyValuePair<string, string>("State", State));
            keyValueData.Add(new KeyValuePair <string, string>("Class", Class));
            keyValueData.Add(new KeyValuePair <string, string>("Client", Client));
            keyValueData.Add(new KeyValuePair <string, string>("Comment", Comment));
            keyValueData.Add(new KeyValuePair <string, string>("Profit", Profit.ToString(System.Globalization.CultureInfo.InvariantCulture)));
            keyValueData.Add(new KeyValuePair <string, string>("StopLoss", StopLoss.ToString(System.Globalization.CultureInfo.InvariantCulture)));

            return(keyValueData);
        }
Beispiel #7
0
        private void LoadHoldings()
        {
            //Load held assets, stoploss amts, from SQLite for each period:
            AddHoldingsTable("period5m");
            AddHoldingsTable("period20m");
            AddHoldingsTable("period1h");
            AddHoldingsTable("period4h");
            AddHoldingsTable("period12h");
            AddHoldingsTable("OpenOrders");


            //REGISTER EXISTING STOPLOSS RATES FOR EACH HOLDING
            foreach (DataTable dt in Holdings.Tables)
            {
                if (dt.TableName == "OpenOrders")
                {
                    continue;
                }

                foreach (DataRow row in dt.Rows)
                {
                    var stopLoss = new StopLoss((string)row["MarketDelta"], Convert.ToDecimal(row["StopLossRate"]), Convert.ToDecimal(row["Qty"]), (a, b, c) => ReCalcStoploss(a, b, c), (a, b) => StopLossExecutedCallback(a, b), dt.TableName, OPTIONS.VITRUAL_MODE);

                    if (OPTIONS.SAFE_MODE)
                    {
                        if (Convert.ToDecimal(row["BoughtRate"]) > stopLoss.StopRate)
                        {
                            stopLoss.StopRate = Convert.ToDecimal(row["BoughtRate"]) * 0.68M;
                        }
                    }
                    //Trace.WriteLine(string.Format("{0}_{1} ... {2} ... {3} ... {4}", stopLoss.CandlePeriod, stopLoss.MarketDelta, stopLoss.Quantity, stopLoss.StopRate, stopLoss.virtualSL));

                    StopLossController.RegisterStoploss(stopLoss, string.Format("{0}_{1}", stopLoss.CandlePeriod, stopLoss.MarketDelta));
                }
            }


            //Load Total From SQLite data:
            LoadTradingTotal();
        }
        protected void LookForEntry()
        {
            if (_macd.MacdUp[0] == 0 && Rising(_rsi) && Rising(_macd.Avg))
            {
                _tradeState    = TradeState.InitialStop;
                _lossLevel     = Low[0] - TickSize * _mmInitialSL;
                _positionPrice = Close[0];
                PositionPrice.Set(_positionPrice);
                StopLoss.Set(_lossLevel);
                SetSignal(1, "going long");
                return;
            }

            if (_macd.MacdDn[0] == 0 && Falling(_rsi) && Falling(_macd.Avg))
            {
                _tradeState    = TradeState.InitialStop;
                _lossLevel     = High[0] + TickSize * _mmInitialSL;
                _positionPrice = Close[0];
                PositionPrice.Set(_positionPrice);
                StopLoss.Set(_lossLevel);
                SetSignal(-1, "going short");
                return;
            }
        }
        void ReleaseDesignerOutlets()
        {
            if (EntryDate != null)
            {
                EntryDate.Dispose();
                EntryDate = null;
            }

            if (EntryPrice != null)
            {
                EntryPrice.Dispose();
                EntryPrice = null;
            }

            if (EntrySetup != null)
            {
                EntrySetup.Dispose();
                EntrySetup = null;
            }

            if (EntrySize != null)
            {
                EntrySize.Dispose();
                EntrySize = null;
            }

            if (EntryType != null)
            {
                EntryType.Dispose();
                EntryType = null;
            }

            if (ExitDate != null)
            {
                ExitDate.Dispose();
                ExitDate = null;
            }

            if (ExitPrice != null)
            {
                ExitPrice.Dispose();
                ExitPrice = null;
            }

            if (Fees != null)
            {
                Fees.Dispose();
                Fees = null;
            }

            if (ProfitLoss != null)
            {
                ProfitLoss.Dispose();
                ProfitLoss = null;
            }

            if (StopLoss != null)
            {
                StopLoss.Dispose();
                StopLoss = null;
            }

            if (TakeProfit != null)
            {
                TakeProfit.Dispose();
                TakeProfit = null;
            }
        }
        public void OnNewCandle(Candle candle)
        {
            _lastCoinValue = CoinValue;
            CoinValue      = candle.Close;

            this.CurrentTrend = Trend();

            EmaDiff.Add(CoinValue);
            if (EmaDiff.IsValid())
            {
                // _emadiff = EmaDiff.Calculate();
                _emadiff = EmaDiff.CurrentValue;
            }

            Roc.Add(CoinValue);
            if (Roc.IsValid())
            {
                Rocdiff = Roc.CurrentValue;     //Roc.Calculate();
            }

            Values.Add(CoinValue);
            if (Values.IsValid())
            {
            }

            /*
             * foreach (MacdItem item in this.MacdList)
             * {
             *  item.Macd.Add(_coinValue);
             *  if (item.Macd.IsValid())
             *  {
             *      item.CurrentValue = item.Macd.Calculate();
             *  }
             * }*/
            //this.Macd122609.Calculate();

            /*
             * if (StopLoss != null) StopLoss.Add(_coinValue);
             * if (StopLossReverse != null) StopLossReverse.Add(1/_coinValue);
             */
            if (StopLoss != null)
            {
                StopLoss.Add(CoinValue);
            }
            if (StopLossReverse != null)
            {
                StopLossReverse.Add(1 / CoinValue);
            }

            /*
             * _macd031001.Add(_coinValue);
             * if (_macd031001.IsValid())
             * {
             *  _macd031001Value = _macd031001.Calculate();
             * }
             */
            Macd122609.Add(CoinValue);
            if (Macd122609.IsValid())
            {
                CurrentMacdValue = Macd122609.CurrentValue;     //Macd122609.Calculate();
            }

            // calcolo trend
            Ema20.Add(candle.Close);
            Ema50.Add(candle.Close);
            Sma200.Add(candle.Close);
        }
        public override TradeAction SuggestedAction(CMarket market)
        {
            /********************************************************************************
            * COSTANTI (evaluator)
            ********************************************************************************/

            //var timeUnit = 15;

            //data corrente (servirebbe la data del ticker, ma vabbè...)
            var now = market.CandleMaker.GetLastCandles()[0].Date;

            var lastCandle = new
            {
                m15 = market.CandleMaker.GetLastCandles()[0],
                h1  = market.CandleMakerHourly.GetLastCandles()[0],
            };

            //valutatore
            var E = Evaluations.EvaluationManager.Instance;

            //formatta i nomi degli indicatori
            Func <string, string> N = (o =>
            {
                return(string.Format("{0}[{1}]", o, this.Name));
            });



            /********************************************************************************
            * COSTANTI
            ********************************************************************************/

            var currentTrend = market.CandleMaker.Analyze.CurrentTrend; //Trend();
            var roclimit     = MainConfiguration.Configuration.AlarmStrongSellBuyRocLimit;
            var macdlimit    = MainConfiguration.Configuration.AlarmStrongSellMacdLimit;

            /********************************************************************************
            * STOP LOSS
            ********************************************************************************/
            if (MainConfiguration.Configuration.EnableStopLoss)
            {
                if (StopLoss.IsSell(this.CoinValue))
                {
                    if (currentTrend == TechnicalAnalysis.Trend.Fall)
                    {
                        StopLoss.Reset();
                        StopLoss.SellCounter++;

                        //EVAL: se uso lo stoploss, sto prevedendo che il prezzo scenda, anche di poco
                        E.Add(N("stoploss"), CreatePrediction(now, TradeAction.StrongSell), timeUnit);
                    }
                }
            }

            if (!IsValid())
            {
                //AnalyticsTools.Call("notyetready");
                return(TradeAction.Unknown);
            }



            /********************************************************************************
            * ROC (non ancora usato)
            ********************************************************************************/
            if (true)
            {
                var rocSpeed = Roc.Derivative.CurrentSpeed;
                if (Rocdiff > roclimit && rocSpeed <= 0 && currentTrend == TechnicalAnalysis.Trend.Fall)
                {
                    //LogTrade.Note = "inversione: vendere";
                    //EVAL: se dico di vendere, vuol dire che il prezzo scenderà, anche di poco
                    E.Add(N("-(rocdiff;rocspeed)"), CreatePrediction(now, TradeAction.Sell), timeUnit);

                    if (CurrentMacdValue > macdlimit)
                    {
                        //EVAL: questo è un rafforzativo, quindi mi aspetto un grande ribasso
                        E.Add(N("++(rocdiff;rocspeed;Macd122609)"), CreatePrediction(now, TradeAction.StrongSell), timeUnit);

                        //return TradeAction.StrongSell;
                    }
                }
                if (Rocdiff < -roclimit && rocSpeed <= 0 && currentTrend == TechnicalAnalysis.Trend.Raise)
                {
                    //LogTrade.Note = "inversione: comprare";
                    //EVAL: se dico di comprare, vuol dire che il prezzo salirà, anche di poco
                    E.Add(N("+(rocdiff;rocspeed)"), CreatePrediction(now, TradeAction.Buy), timeUnit);

                    if (CurrentMacdValue < -macdlimit)
                    {
                        //EVAL: questo è un rafforzativo, quindi mi aspetto un grande rialzo
                        E.Add(N("++(rocdiff;rocspeed;Macd122609)"), CreatePrediction(now, TradeAction.StrongBuy), timeUnit);
                        // return TradeAction.StrongBuy;
                    }
                }
            }
            if (true)
            {
                // se si mette a true, questo garantisce 12k e 15btc (l'altro pezzo sul roc va messo in tuning
                if (Rocdiff > roclimit && currentTrend == TechnicalAnalysis.Trend.Fall)
                {
                    //LogTrade.Note = "inversione: vendere";
                    //EVAL: se dico di vendere, vuol dire che il prezzo scenderà, anche di poco
                    E.Add(N("-(rocdiff)"), CreatePrediction(now, TradeAction.Sell), timeUnit);

                    if (CurrentMacdValue > 2)
                    {
                        //EVAL: questo è un rafforzativo, quindi mi aspetto un grande ribasso
                        E.Add(N("--(rocdiff;Macd122609)"), CreatePrediction(now, TradeAction.StrongSell), timeUnit);
                        //return TradeAction.StrongSell;
                    }
                }
                if (Rocdiff < -roclimit && currentTrend == TechnicalAnalysis.Trend.Raise)
                {
                    //LogTrade.Note = "inversione: comprare";
                    //EVAL: se dico di comprare, vuol dire che il prezzo salirà, anche di poco
                    E.Add(N("+(rocdiff;rocspeed)"), CreatePrediction(now, TradeAction.Buy), timeUnit);

                    if (CurrentMacdValue < -2)
                    {
                        //EVAL: questo è un rafforzativo, quindi mi aspetto un grande rialzo
                        E.Add(N("++(rocdiff;rocspeed;Macd122609)"), CreatePrediction(now, TradeAction.StrongBuy), timeUnit);
                        // return TradeAction.StrongBuy;
                    }
                }

                /********************************************************************************
                * ALLARMI
                ********************************************************************************/

                var emadiffValue = EmaDiff.CurrentValue;  //EmaDiff.Calculate(); // potrebbe essere inutile (lo abbiamo già)
                var macdValue    = this.CurrentMacdValue; // potrebbe essere inutile (lo abbiamo già)
                //var roclimit = 5.0M;
                if (Math.Sign(emadiffValue) == Math.Sign(macdValue))
                {
                    var limit = MainConfiguration.Configuration.AlarmStrongSellBuyLimit; // occorre capire che valori sono i migliori


                    if ((emadiffValue < -limit && macdValue < -limit))
                    {
                        //LogTrade.Note = ("suggestion: (emadiffValue < -limit && macdValue < -limit)");
                        // AnalyticsTools.Call("ema;macd;limit;-");
                        //return TradeAction.StrongSell;

                        //EVAL:
                        E.Add(N("--(ema;macd;limit;)"), CreatePrediction(now, TradeAction.StrongSell), timeUnit);
                    }

                    if (emadiffValue > limit && macdValue > limit)
                    {
                        //LogTrade.Note = ("suggestion:  (emadiffValue > limit && macdValue > limit)");
                        // AnalyticsTools.Call("ema;macd;limit;+");
                        // return TradeAction.StrongBuy;

                        //EVAL:
                        E.Add(N("++(ema;macd;limit;)"), CreatePrediction(now, TradeAction.StrongBuy), timeUnit);
                    }

                    if (emadiffValue < -1 && macdValue < -1)
                    {
                        //LogTrade.Note = ("suggestion:  (emadiffValue < -1 && macdValue < -1)");
                        // AnalyticsTools.Call("ema;macd;-1");
                        // return TradeAction.Sell;

                        //EVAL:
                        E.Add(N("-(ema;macd;-1;)"), CreatePrediction(now, TradeAction.Sell), timeUnit);
                    }

                    if (emadiffValue > 1 && macdValue > 1)
                    {
                        //  AnalyticsTools.Call("ema;macd;+1");
                        //LogTrade.Note = ("suggestion:  (emadiffValue > 1 && macdValue > 1)");
                        //return TradeAction.Buy;

                        //EVAL:
                        E.Add(N("+(ema;macd;+1;)"), CreatePrediction(now, TradeAction.Buy), timeUnit);
                    }
                }



                var poll = new Poll();

                /********************************************************************************
                * MACD
                ********************************************************************************/
                //foreach (MacdItem item in this.MacdList)
                {
                    poll.Add(Macd122609.SuggestedAction(CurrentMacdValue, currentTrend));
                    CUtility.Log(string.Format("MACD   {0}", Math.Round(CurrentMacdValue, 4).ToString(CultureInfo.InvariantCulture)));
                }

                /********************************************************************************
                * EMADIFF
                ********************************************************************************/
                var emadiffSuggestion = EmaDiff.SuggestedAction(CurrentEmaDiff, currentTrend);
                poll.Add(emadiffSuggestion);
                CUtility.Log(string.Format("EMADIFF {0}", Math.Round(CurrentEmaDiff, 4).ToString(CultureInfo.InvariantCulture)));


                /********************************************************************************
                * DECISION
                ********************************************************************************/
                //LogTrade.Note = "poll";

                var result = poll.Result();

                if (true)
                {
                    // questo sistema di sicurezza non genera troppi problemi, ma non aumenta il reddito
                    // pero' aumenta la media dei redditi

                    // sistema di sicurezza da testare
                    const decimal securitylimit = 1.5M; // va bene cosi'


                    if (result == TradeAction.Buy && market.Buy >= securitylimit * LogTrade.BuyAt && LogTrade.BuyAt > 0 &&
                        currentTrend == TechnicalAnalysis.Trend.Raise)
                    {
                        //  AnalyticsTools.Call("expensive");
                        //  return TradeAction.Hold;

                        //EVAL: in realtà, "expensive" scommette sul fatto che può comprare a meno
                        E.Add(N("expensive"), new Evaluations.Prediction()
                        {
                            Date  = now,
                            Type  = Evaluations.PredictionType.LessThan,
                            Value = this.CoinValue * (1 - 0.01M)
                        }, timeUnit);
                    }

                    if (result == TradeAction.Sell && market.Sell <= securitylimit * LogTrade.SellAt && LogTrade.SellAt > 0 &&
                        currentTrend == TechnicalAnalysis.Trend.Fall)
                    {
                        // AnalyticsTools.Call("cheap");
                        //  return TradeAction.Hold;

                        //EVAL: in realtà, "cheap" scommette sul fatto che può vendere a più
                        E.Add(N("cheap"), new Evaluations.Prediction()
                        {
                            Date  = now,
                            Type  = Evaluations.PredictionType.GreatherThan,
                            Value = this.CoinValue * (1 + 0.01M)
                        }, timeUnit);
                    }
                }

                if (result != TradeAction.Hold)
                {
                    // AnalyticsTools.Call("poll " + result.ToString());
                }

                //return result;

                //EVAL: globale, ovvero cosa fa l'algoritmo
                // E.Add("GLOBAL", CreatePrediction(now, result), timeUnit);

                return(TradeAction.Unknown);
            }
        }