Overall Statistics
Total Trades
76
Average Win
0.34%
Average Loss
-0.01%
Compounding Annual Return
5.484%
Drawdown
6.500%
Expectancy
33.711
Net Profit
6.975%
Sharpe Ratio
0.603
Loss Rate
3%
Win Rate
97%
Profit-Loss Ratio
34.68
Alpha
0.049
Beta
-0.014
Annual Standard Deviation
0.079
Annual Variance
0.006
Information Ratio
-0.369
Tracking Error
0.138
Treynor Ratio
-3.384
Total Fees
$76.00
using System.Drawing; // for Color
namespace QuantConnect 
{   
    public class Teststochnoloss : QCAlgorithm
    {
    	private int _kPeriod = 14;
        private	int _dPeriod = 3;
        private int _overBought = 20;  //a optimiser
        
        private decimal _targetProfit = 0.01m;    //0.02m=0.2%           //Target profit for strategy. When achieve this exit.
        //private decimal _weight = 0m;
        
        private Dictionary<Symbol, Stochastic> _sto = new Dictionary<Symbol, Stochastic>();
        private Dictionary<Symbol, decimal> _targetPrice = new Dictionary<Symbol, decimal>();
        
        public override void Initialize() 
        {
	        SetStartDate(2016, 1, 16);         
            SetCash(10000);              // Cash allocation
            //SetBenchmark("AAPL");        // Customize benchmark
            SetWarmup(20);               // Warmup for the stochastic
          	
    		//ini broker model
			SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash);
            
            foreach(var ticker in "IRBT,JLL,DIS".Split(',')) //IRBT,JLL,HAIN,DIS
            {
            	// Subscribe the ticker with resolution higher than 30 min (minute, for example)
            	var security = AddSecurity(SecurityType.Equity, ticker, Resolution.Minute,fillDataForward: false, extendedMarketHours: false);
            	//AddSecurity(SecurityType.Equity, ticker, Resolution.Minute);
            	security.SetLeverage(1m);
            	//- Create consolidators:
            	var consolidator = new TradeBarConsolidator(TimeSpan.FromMinutes(30));
            	
            	// Create indicator
            	var sto = new Stochastic("STO_" + ticker, 14, _kPeriod, _dPeriod);
            	
            	// Add indicator to a dictionary to later reference
            	_sto.Add(ticker, sto);
            	
            	_targetPrice.Add(ticker, 0m);
            	
            	// Register indicator for automatic updates at consolidator frequency
            	RegisterIndicator(ticker, sto, consolidator);
            	
            	// Subscribe consolidator to this ticker.
            	SubscriptionManager.AddConsolidator(ticker, consolidator);
            	
            	// 
            	consolidator.DataConsolidated += OnConsolidorData;
            	
            	var plotter = new Chart(ticker);
            	plotter.AddSeries(new Series("D", SeriesType.Line, " ",Color.Red));
            	plotter.AddSeries(new Series("K", SeriesType.Line, " ",Color.Blue));
            	plotter.AddSeries(new Series("Over Bought", SeriesType.Line, " ",Color.Black));
            	plotter.AddSeries(new Series("Buy", SeriesType.Scatter, index:0));
            	plotter.AddSeries(new Series("Sell", SeriesType.Scatter, index:0));// sur graph plot pas rouge
            
            	AddChart(plotter);
          	}
          	
          	//_weight = 1m / Securities.Count;
        }

        public void OnData(TradeBars data) 
        {   
            if (IsWarmingUp) return;
            
            foreach (var bar in data.Values)
            {
            	var close = bar.Close;
            	var symbol = bar.Symbol;
            	int nbsec=-1;
            	if (!Portfolio[symbol].Invested) 
            	{
            		var sto = _sto[symbol];
            		if (!sto.IsReady) continue;
            		
            		if (sto.StochK > sto.StochD && sto.StochD < _overBought)
                	{
                		//SetHoldings(symbol, _weight);
                		
                		
	                		foreach(var security in Securities.Values) {
		    						if(!security.Invested) {
		    							nbsec++; //number of non invested securities
		    							//Debug("nbsec " + security.Symbol);
		    							}
	                		}
	                	
	                		
	                	//Debug("nbsec " + nbsec);
	                	//Debug("nb securities " + (Securities.Count-1));
	                	//Quit();
	                	if(nbsec<(Securities.Count-1))
	                	{
	                	int quantity = ((int)Math.Floor(Portfolio.Cash /bar.Open))/(nbsec);
	                	if(quantity==1)
	                	{
	                	Debug("cash " + Portfolio.Cash + "open " + bar.Open + "nb secu" + nbsec);
	                	}
            			Order(symbol, quantity);
	                	}
	            		else
	            		{
	            		int quantity = ((int)Math.Floor(Portfolio.Cash / bar.Open))/(Securities.Count-1);
	            		if(quantity==1)
	                	{
	                	Debug("cash " + Portfolio.Cash + "open " + bar.Open);
	                	Debug("nb securities " + (Securities.Count-1));
	                	}
            			Order(symbol, quantity);		
	            		}
	                	
                	}
            	}
            	else
            	{
            		if (close >= _targetPrice[symbol])
            		{
            			Liquidate(symbol);
            		}
            	}
            }
        }
    
    	// Every 30 minutes data arrives here
    	public void OnConsolidorData(object s, TradeBar bar)
    	{
    		var sto = _sto[bar.Symbol];
           	Plot(bar.Symbol, "Price", bar.Close);
			Plot(bar.Symbol,"D", sto.StochD);
        	Plot(bar.Symbol,"K", sto.StochD);
        	Plot(bar.Symbol,"Over Bought", _overBought);
    	}
    	
    	public override void OnOrderEvent(OrderEvent orderEvent)
    	{
    		if (orderEvent.Status == OrderStatus.Filled)
    		{
    			var symbol = orderEvent.Symbol;
    			var price = orderEvent.FillPrice;
    			
    			if (orderEvent.Direction == OrderDirection.Buy)
    			{
    				_targetPrice[symbol] = price * (1 + _targetProfit);
           			Plot(symbol, "Buy", price);
                	Log(string.Format("{0} -> Buy {1} for {2}, target at {3}", 
                		Time.ToString("Y"), symbol, price, _targetPrice[symbol]));
    			}
    			
    			if (orderEvent.Direction == OrderDirection.Sell)
    			{
    				Plot(symbol, "Sell", price);
    			}
    		}
    	}
    }
}