namespace SampleHistoryTesting
{
    using System;
    using System.ComponentModel;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Globalization;
    using System.IO;
    using System.Threading;
    using System.Windows;
  
    using System.Windows.Forms;
    using System.Windows.Threading;
    
    using Ecng.Common;
   
	using StockSharp.Algo;
	using StockSharp.Algo.Candles;
	using StockSharp.Algo.Indicators;
	using StockSharp.Algo.Indicators.Trend;
    using StockSharp.Logging;
   
    using StockSharp.Algo.Commissions;
    using StockSharp.Algo.Indicators.Misc;
    using StockSharp.Algo.Indicators.Oscillator;
	
	using StockSharp.Algo.Strategies;
	using StockSharp.BusinessEntities;
    using System.Data.OleDb;
    using StockSharp.Xaml;

    using Ecng.Collections;
    using Ecng.Common;
    using Ecng.Xaml;
    using Ecng.ComponentModel;


    class SmaStrategy : Strategy
    {


        public static MainWindow Instance { get; private set; }
        private readonly CandleSeries _series;
        private bool _isShortLessThenLong;
        private CandleManager candleManager;
        private ChartIndicatorElement _longMaElem;
        private ChartIndicatorElement _shortMaElem;
        private ChartCandleElement _candlesElem;


        public SimpleMovingAverage Sma24 { get; private set; }
        public SimpleMovingAverage Sma50 { get; private set; }
       

        public string Sostoyanie;
        private CommissionManager _commissionManager = new CommissionManager();
        public decimal comission;

        
        public decimal cena_zayavki;
       
        public Order order_close_position { get; set; }
        
        public decimal proskalz;
        public decimal vol_kontr;
        public OleDbConnection vcon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\C#Programs\БД\Test5.accdb");
        public decimal candle_close;
       
        public decimal takeprofit;

       
        private readonly object _locker = new object();
        
        public bool START = false;
       
        public decimal dir;

        public decimal EntryPrice;
        public Order order_open_long { get; set; }
        public Order order_open_short { get; set; }
        public Order order_close_long { get; set; }
        public Order order_close_short { get; set; }
        public int nomersdelki;
        public decimal sma24;
        public decimal sma50;
        public bool Propusk;

        public SmaStrategy(CandleSeries series, SimpleMovingAverage Sma24_st, SimpleMovingAverage Sma50_st)
        {
            _series = series;


            Sma24 = Sma24_st;
            Sma50 = Sma50_st;
            
        }




        protected override void OnStarted()
        {
            //vcon.Open();
            CommissionRule commissionRule = new CommissionRule { Type = CommissionTypes.PerTradeVolume, Value = new Unit(3m) };
            _commissionManager.Rules.Add(commissionRule);
           
            Sostoyanie = "кэш";
           
            takeprofit  = decimal.Parse(MainWindow.Instance.takeprofit_form.Text);
            proskalz = decimal.Parse(MainWindow.Instance.proskalz.Text);
            vol_kontr = decimal.Parse(MainWindow.Instance.vol_lotov.Text);
            vcon.Open();
           
            // Создание элемента графика представляющего свечки
            _candlesElem = new ChartCandleElement();
            MainWindow.Instance._area.Elements.Add(_candlesElem);

            //MainWindow.Instance._area_ind.Elements.Add(_longMaElem);
            //MainWindow.Instance._area_ind.Elements.Add(_shortMaElem);

         
            //this
            //    .WhenNewMyTrades()
            //    .Do(ProcessNewTrades)
            //    .Apply(this);
            _series
                .WhenCandlesFinished()
                .Do(ProcessCandle)
                .Apply(this);
            
            base.OnStarted();
        }

             
        private void ProcessCandle(Candle candle)
        {

          //  if (candle.State == CandleStates.Finished) MainWindow.Instance.GuiAsync(() => MainWindow.Instance.Chart.ProcessCandle(_candlesElem, candle));
            Sma24.Process(candle.ClosePrice);
            Sma50.Process(candle.ClosePrice);


            sma24 = Sma24.GetValue<decimal>(0);
            sma50 = Sma50.GetValue<decimal>(0);

            MainWindow.Instance.GuiAsync(() =>
            {
                MainWindow.Instance.trades_time.Text = Security.LastTrade.Time.ToString();
                MainWindow.Instance.pos2_form.Text = Sostoyanie;
                MainWindow.Instance.position_form.Text = Position.ToString();
            });

         
            if (!START)
            {
                if (Sma24.Container.Count > 2)
                {
                    START = true;
                    Security
               .WhenNewTrades()
               .Do(ProcessNewTrade)
               .Apply(this);

                }
            }

        }
     
        private void ProcessNewTrade()
        {
            if (Security.LastTrade == null)
            { goto propusk2; }

            if (Security.LastTrade.Time.Hour == 19 && Security.LastTrade.Time.Minute == 0 && Security.LastTrade.Time.Second < 10)
            { goto propusk2; }

            switch (Sostoyanie)
            {
                case "кэш":
                    {
                        if (Security.LastTrade.Price > sma24)
                        {
                            Sostoyanie = "Long";
                            Buy_Order(vol_kontr);
                        }
                        else if (Security.LastTrade.Price < sma24)
                        {
                            Sostoyanie = "Short";
                            Sell_Order(vol_kontr);
                        }
                    }
                    break;
                case "Long":
                    {
                        if (Security.LastTrade.Price < sma24)
                        {
                            Sostoyanie = "кэш";
                            Sell_Order(vol_kontr);
                        }
                    }
                    break;
                case "Short":
                    {
                        if (Security.LastTrade.Price > sma24)
                        {
                            Sostoyanie = "кэш";
                            Buy_Order(vol_kontr);
                        }
                    }
                    break;
            }

        propusk2:

            //MainWindow.Instance.GuiAsync(() =>
            //{

            //    MainWindow.Instance.trades_time.Text = Security.LastTrade.Time.ToString();
            //    //MainWindow.Instance.now_time.Text = DateTime.Now.ToString();
            //    //MainWindow.Instance.SMA_znachenie_form.Text = Sma.LastValue.ToString();
            //    MainWindow.Instance.pos2_form.Text = pos;
            //    //MainWindow.Instance.ROC_form.Text = ROC.LastValue.ToString();
            //    MainWindow.Instance.position_form.Text = Position.ToString();
            //    MainWindow.Instance.komiss_form.Text = comission.ToString();

            //});
            Propusk = true;
        }

        private void Buy_Order(decimal volume)
        {

            EntryPrice = Security.LastTrade.Price; ;

            this.AddInfoLog("Сигнал на покупку");
            nomersdelki++;
            order_open_long = this.CreateOrder(OrderDirections.Buy, Security.LastTrade.Price + proskalz, volume);
            order_open_long.Security = Security;
            this.RegisterOrder(order_open_long);
            order_open_long
                                .WhenMatched()
                                .Do(pos_change_long)
                                .Apply(this);

            this.AddInfoLog(PnLManager.PnL.ToString());
            //string vsql = string.Format("insert into Rez2 (nomer_sdelki, data_vxoda,vremya_vxoda, cena_vxoda, High, Low,stop_price) Values ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            //          (nomersdelki), (Security.LastTrade.Time.ToString("dd.MM")), (Security.LastTrade.Time.ToString("HH.mmss")), (order_open_long.Price.ToString()), (candle_high),(candle_low),(stop_price));


            //OleDbCommand vcom = new OleDbCommand(vsql, vcon);
            //vcom.ExecuteNonQuery();
        }


        private void Sell_Order(decimal volume)
        {
            EntryPrice = Security.LastTrade.Price;
            this.AddInfoLog("Сигнал на продажу");
            nomersdelki++;
            order_open_short = this.CreateOrder(OrderDirections.Sell, Security.LastTrade.Price - proskalz, volume);
            order_open_short.Security = Security;

            this.RegisterOrder(order_open_short);
            order_open_short
                                .WhenMatched()
                                .Do(pos_change_short)
                                .Apply(this);
            //string vsql = string.Format("insert into Rez2 (nomer_sdelki, data_vxoda,vremya_vxoda, cena_vxoda, High, Low,stop_price) Values ({0}, {1}, {2}, {3}, {4}, {5}, {6})",
            //          (nomersdelki), (Security.LastTrade.Time.ToString("dd.MM")), (Security.LastTrade.Time.ToString("HH.mmss")), (order_open_long.Price.ToString()), (candle_high), (candle_low), (stop_price));
            //OleDbCommand vcom = new OleDbCommand(vsql, vcon);
            //vcom.ExecuteNonQuery();
        }

      

        private void pos_change_short()
        {
            this.AddInfoLog("pos_change_short");
            
            //string vsql = string.Format("insert into Sdelki (nomer_sdelki, data_vxoda,vremya_vxoda, cena_vxoda) Values ({0}, {1}, {2}, {3})",
            //    (nomersdelki), (Security.LastTrade.Time.ToString("dd.MM")), (Security.LastTrade.Time.ToString("HH.mmss")), (EntryPrice));

            //OleDbCommand vcom = new OleDbCommand(vsql, vcon);
            //vcom.ExecuteNonQuery();

            //string vsql2 = string.Format("Update ([Sdelki]) Set vid_pozicii = '" + Sostoyanie + "' Where ([nomer_sdelki] = @nomersdelki)");

            //OleDbCommand vcom2 = new OleDbCommand(vsql2, vcon);
            //vcom2.Parameters.AddWithValue("@nomersdelki", nomersdelki);
            //vcom2.ExecuteNonQuery();

        }
        private void pos_change_long()
        {

            this.AddInfoLog("pos_change_long");
           
            //string vsql = string.Format("insert into Sdelki (nomer_sdelki, data_vxoda,vremya_vxoda, cena_vxoda, SMA) Values ({0}, {1}, {2}, {3}, {4})",
            //        (nomersdelki), (Security.LastTrade.Time.ToString("dd.MM")), (Security.LastTrade.Time.ToString("HH.mmss")), (EntryPrice), (Sma24.GetValue<decimal>(0)));


            //OleDbCommand vcom = new OleDbCommand(vsql, vcon);
            //vcom.ExecuteNonQuery();

            //string vsql2 = string.Format("Update ([Sdelki]) Set vid_pozicii = '" + Sostoyanie + "' Where ([nomer_sdelki] = @nomersdelki)");

            //OleDbCommand vcom2 = new OleDbCommand(vsql2, vcon);
            //vcom2.Parameters.AddWithValue("@nomersdelki", nomersdelki);
            //vcom2.ExecuteNonQuery();

        }
    }
     
}