Overall Statistics
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;

namespace Quant
{
    /// <summary>
    /// Provides a base class for alpha models.
    /// </summary>
    public class AlphaModell : IAlphaModell, INamedModel
    {
        /// <summary>
        /// Defines a name for a framework model
        /// </summary>
        public virtual string Name { get; set; }

        public AlphaModell()
        {
            Name = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// Updates this alpha model with the latest data from the algorithm.
        /// This is called each time the algorithm receives data for subscribed securities
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="data">The new data available</param>
        /// <returns>The new insights generated</returns>
        public virtual IEnumerable<Insight> Update(QCAlgorithm algorithm, OrderEvent orderEvent, Slice slice)
        {
            throw new System.NotImplementedException("Types deriving from 'AlphaModel' must implement the 'IEnumerable<Insight> Update(QCAlgorithm, Slice) method.");
        }

        /// <summary>
        /// Event fired each time the we add/remove securities from the data feed
        /// </summary>
        /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
        /// <param name="changes">The security additions and removals from the algorithm</param>
        public virtual void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
        {
        }
    }
}
using System.Collections.Generic;
using QuantConnect.Data;

namespace Quant
{
    /// <summary>
    /// Algorithm framework model that produces insights
    /// </summary>
    public interface IAlphaModell : INotifiedSecurityChanges
    {
        /// <summary>
        /// Updates this alpha model with the latest data from the algorithm.
        /// This is called each time the algorithm receives data for subscribed securities
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="data">The new data available</param>
        /// <returns>The new insights generated</returns>
        IEnumerable<Insight> Update(QCAlgorithm algorithm, OrderEvent orderEvent, Slice slice);
    }
}
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using System.Linq;
using QuantConnect;
using QuantConnect.Securities.Future;
using QuantConnect.Interfaces;
using QuantConnect.Indicators;
using QuantConnect.Securities;
using QuantConnect.Algorithm;
using QuantConnect.Algorithm.Framework.Execution ;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using Quant;

namespace Quant
{
public partial class Algorithm : QCAlgorithm
{
	private String[] futureSymbols = new[] {"ES", "YM"};
	private Dictionary<Symbol, FuturesChain> contract_chains = new Dictionary<Symbol, FuturesChain>();
	private Dictionary<Symbol, Future> contracts = new Dictionary<Symbol, Future>();

	public OrderTicket EntryOrder { get; set; }
	public Func<QCAlgorithm, string, decimal, OneCancelsOtherTicketSet> OnOrderFilledEvent { get; set; }
	public OneCancelsOtherTicketSet ProfitLossOrders { get; set; }
	
	private Symbol _YM;
	private Symbol _ES;
	
public override void Initialize()
{
	SetStartDate(2000, 01, 01);
    SetEndDate(2010, 01, 01);
    SetCash(1000000);

foreach (var futureSymbol in futureSymbols) 
{
	Debug($"Registering {futureSymbol}");
	Future fut = AddFuture(futureSymbol, Resolution.Minute);
	fut.SetFilter(universe => universe.FrontMonth());
}

_ES = QuantConnect.Symbol.Create("ES", SecurityType.Future, Market.USA);
_YM = QuantConnect.Symbol.Create("YM", SecurityType.Future, Market.USA);

SetSecurityInitializer(x => x.SetSlippageModel(new CustomSlippageModel(this)));
SetBrokerageModel(BrokerageName.AlphaStreams);
SetExecution(new VolumeWeightedAveragePriceExecutionModel());

AddRiskManagement(new MaximumUnrealizedProfitPercentPerSecurity(0.1m));
AddRiskManagement(new MaximumDrawdownPercentPerSecurity(0.1m));

}

public class FuturesUniverseSelectionModel : FutureUniverseSelectionModel
{
	public FuturesUniverseSelectionModel(Func<DateTime, IEnumerable<Symbol>> futureChainSymbolSelector)
	:base(TimeSpan.FromDays(1), futureChainSymbolSelector){}
		
	public FutureFilterUniverse filter(FutureFilterUniverse filter){
	return filter.Expiration(TimeSpan.Zero, TimeSpan.FromDays(182)).OnlyApplyFilterAtMarketOpen();}
}

public class CustomSlippageModel : ISlippageModel
{
            private readonly QCAlgorithm _algorithm;
            
            public RollingWindow<decimal> High = new RollingWindow<decimal>(2);
            public RollingWindow<decimal> Low = new RollingWindow<decimal>(2);
            public RollingWindow<decimal> Volume = new RollingWindow<decimal>(2);
			
            public CustomSlippageModel(QCAlgorithm algorithm)
            {
				_algorithm = algorithm;
			}

            public decimal GetSlippageApproximation(Security asset, Order order)
            {			
    			High.Add(asset.High);
    			Low.Add(asset.Low);
    			Volume.Add(asset.Volume);
    			
    			var orderVolume = order.AbsoluteQuantity;
    			var slippage = (High[0]-Low[0]) * 0.01m / (Volume[0]/orderVolume);
    			
    			if (asset.Symbol.Value.StartsWith("ES"))
    			{
    			if (((High[0]-Low[0]) * 0.01m / (Volume[0]/orderVolume)) < VarES.minprizefluct)
    			{
    				return VarES.minprizefluct ;
    			}
    			}
    			
    			if (asset.Symbol.Value.StartsWith("YM"))
    			{
    			if (((High[0]-Low[0]) * 0.01m / (Volume[0]/orderVolume)) < VarES.minprizefluct)
    			{
    				return VarYM.minprizefluct ;
    			}
    			}
    			
				return slippage;
            }
}
}
}
using QuantConnect.Algorithm;

namespace Quant
{
public class OneCancelsOtherTicketSet
{
    public OneCancelsOtherTicketSet(params OrderTicket[] orderTickets)
        {
            this.OrderTickets = orderTickets;
        }

        private OrderTicket[] OrderTickets { get; set; }

        public void Filled()
        {
            // Cancel all the outstanding tickets.
            foreach (var orderTicket in this.OrderTickets)
            {
                if (orderTicket.Status == OrderStatus.Submitted)
                {
                    orderTicket.Cancel();
                }
            }
        }
        
}
}
namespace Quant
{
public static class VarES
{
	public const decimal minprizefluct = 0.25m ;
	
	public const decimal TPLong = 1.001m ;
	public const decimal SLLong = 0.972m ;
	
	public const decimal TPShort = 1.001m ;
	public const decimal SLShort = 0.972m ;
}
}
namespace Quant
{
public static class VarYM
{
	public const decimal minprizefluct = 1m ;

	public const decimal TPLong = 1.0005m ;
	public const decimal SLLong = 0.94m ;
	
	public const decimal TPShort = 1.0005m ;
	public const decimal SLShort = 0.94m ;
}
}
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using System.Linq;
using QuantConnect;
using QuantConnect.Securities.Future;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using Quant;

namespace Quant
{

public partial class Algorithm_ES : AlphaModell
{

	public RollingWindow<decimal> BidPriceES = new RollingWindow<decimal>(3);
    public RollingWindow<decimal> AskPriceES = new RollingWindow<decimal>(3);
    public RollingWindow<decimal> VolumeES = new RollingWindow<decimal>(3);

    public OrderTicket EntryOrder { get; set; }

    private readonly Symbol _symbol;
    public Algorithm_ES(Symbol symbol)
    {
        _symbol = symbol;
    }
    
    public Func<QCAlgorithm, string, decimal, OneCancelsOtherTicketSet> OnOrderFilledEvent { get; set; }
    public OneCancelsOtherTicketSet ProfitLossOrders { get; set; }

public override IEnumerable<Insight> Update(QCAlgorithm algo_ES, OrderEvent orderEvent, Slice slice)
{
	
	       	if (EntryOrder != null)
            {
                this.EntryOrder = null;
            }
            
            if (orderEvent.Status == OrderStatus.Filled || orderEvent.Status == OrderStatus.PartiallyFilled)
            {
                if (this.OnOrderFilledEvent != null)
                {
                    this.ProfitLossOrders = OnOrderFilledEvent(algo_ES, orderEvent.Symbol, orderEvent.FillPrice);
                    OnOrderFilledEvent = null;
                }
                
                else
                
                if (this.ProfitLossOrders != null)
                {
                    this.ProfitLossOrders.Filled();
                    this.ProfitLossOrders = null;
                }
            }
            
	var accountCurrencyCash = algo_ES.Portfolio.TotalPortfolioValue;

	var Insight = new List<Insight>();
	
    foreach(var chain in slice.FutureChains)
    {

    // remplacer les lettre entre guillemet par l'abreviation correspondant au contract analysé. 
	if (chain.Value.Symbol.StartsWith("ES"))
    {
	var ES = (from futuresContract in chain.Value.OrderBy(x => x.Expiry)
	where futuresContract.Expiry > algo_ES.Time.Date.AddDays(1) 
	select futuresContract).FirstOrDefault();
    
    if (ES != null)
	{
		
	BidPriceES.Add(ES.BidPrice);
	AskPriceES.Add(ES.AskPrice);
	VolumeES.Add(ES.Volume);
	
	if (!BidPriceES.IsReady || !AskPriceES.IsReady || !VolumeES.IsReady)
	continue;

	if (ES.BidPrice != 0 && ES.AskPrice != 0)
	{

	var _quantityy = (decimal)(VolumeES[0]+VolumeES[1]) * 0.00001m;
	
	if (BidPriceES[0]>AskPriceES[1]) 
	{
	this.OnOrderFilledEvent = (algoo_ES, Symbol, FillPrice) =>
	{
	return new OneCancelsOtherTicketSet(
	algoo_ES.LimitOrder(ES.Symbol, -_quantityy, FillPrice * VarES.TPLong, "Profit Long _Target"),
	algoo_ES.StopMarketOrder(ES.Symbol, -_quantityy, FillPrice * VarES.SLLong, "Stop Long _Loss"));
	};
	EntryOrder = algo_ES.MarketOrder(ES.Symbol, _quantityy, false, "Entry");
	break;
	}

	if (AskPriceES[0]<BidPriceES[1]) 
	{
	this.OnOrderFilledEvent = (algoo_ES, Symbol, FillPrice) =>
	{
	return new OneCancelsOtherTicketSet(
	algoo_ES.LimitOrder(ES.Symbol, -_quantityy, FillPrice * VarES.TPShort, "Profit Short _Target"),
	algoo_ES.StopMarketOrder(ES.Symbol, -_quantityy, FillPrice * VarES.SLShort, "Stop Short _Loss"));
	};
	EntryOrder = algo_ES.MarketOrder(ES.Symbol, _quantityy, false, "Entry");
	break;	
	}

	}}}
    
}

return Insight;
}
}
}
using System;
using System.Collections.Generic;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using System.Linq;
using QuantConnect;
using QuantConnect.Securities.Future;
using QuantConnect.Interfaces;
using QuantConnect.Securities;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using Quant;

namespace Quant
{
   
public partial class Algorithm_YM : AlphaModell
{
	
	public RollingWindow<decimal> BidPriceYM = new RollingWindow<decimal>(3);
    public RollingWindow<decimal> AskPriceYM = new RollingWindow<decimal>(3);
    public RollingWindow<decimal> VolumeYM = new RollingWindow<decimal>(3);

    public OrderTicket EntryOrder { get; set; }

    
	private readonly Symbol _symbol;
    public Algorithm_YM(Symbol symbol)
    {
        _symbol = symbol;
    }
	
	public Func<QCAlgorithm, string, decimal, OneCancelsOtherTicketSet> OnOrderFilledEvent { get; set; }
	public OneCancelsOtherTicketSet ProfitLossOrders { get; set; }
	
public override IEnumerable<Insight> Update(QCAlgorithm algo_YM, OrderEvent orderEvent, Slice slice)
{
	
	if (EntryOrder != null)
            {
                this.EntryOrder = null;
            }
            
            if (orderEvent.Status == OrderStatus.Filled || orderEvent.Status == OrderStatus.PartiallyFilled)
            {
                if (this.OnOrderFilledEvent != null)
                {
                    this.ProfitLossOrders = OnOrderFilledEvent(algo_YM, orderEvent.Symbol, orderEvent.FillPrice);
                    OnOrderFilledEvent = null;
                }
                
                else
                
                if (this.ProfitLossOrders != null)
                {
                    this.ProfitLossOrders.Filled();
                    this.ProfitLossOrders = null;
                }
            }
	
	var accountCurrencyCash = algo_YM.Portfolio.TotalPortfolioValue;
	var Insight = new List<Insight>();

    foreach(var chain in slice.FutureChains)
    {

    // remplacer les lettre entre guillemet par l'abreviation correspondant au contract analysé. 
	if (chain.Value.Symbol.StartsWith("YM"))
    {
	var YM = (from futuresContract in chain.Value.OrderBy(x => x.Expiry)
	where futuresContract.Expiry > algo_YM.Time.Date.AddDays(1) 
	select futuresContract).FirstOrDefault();
    
    if (YM != null)
	{
		
	BidPriceYM.Add(YM.BidPrice);
	AskPriceYM.Add(YM.AskPrice);
	VolumeYM.Add(YM.Volume);
	
	if (!BidPriceYM.IsReady || !AskPriceYM.IsReady || !VolumeYM.IsReady)
	continue;

	if (YM.BidPrice != 0 && YM.AskPrice != 0)
	{

	var _quantityy = (decimal)(VolumeYM[0]+VolumeYM[1]) * 0.001m;
	
	if (BidPriceYM[0]>AskPriceYM[1]) 
	{
	this.OnOrderFilledEvent = (algoo_YM, Symbol, FillPrice) =>
	{
	return new OneCancelsOtherTicketSet(
	algoo_YM.LimitOrder(YM.Symbol, -_quantityy, FillPrice * VarYM.TPLong, "Profit Long _Target"),
	algoo_YM.StopMarketOrder(YM.Symbol, -_quantityy, FillPrice * VarYM.SLLong, "Stop Long _Loss"));
	};
	EntryOrder = algo_YM.MarketOrder(YM.Symbol, _quantityy, false, "Entry");
	break;
	}
	
	if (AskPriceYM[0]<BidPriceYM[1]) 
	{
	this.OnOrderFilledEvent = (algoo_YM, Symbol, FillPrice) =>
	{
	return new OneCancelsOtherTicketSet(
	algoo_YM.LimitOrder(YM.Symbol, -_quantityy, FillPrice * VarYM.TPShort, "Profit Short _Target"),
	algoo_YM.StopMarketOrder(YM.Symbol, -_quantityy, FillPrice * VarYM.SLShort, "Stop Short _Loss"));
	};
	EntryOrder = algo_YM.MarketOrder(YM.Symbol, _quantityy, false, "Entry");
	break;	
	}

	}}}
}
return Insight;
}
}
}
using Python.Runtime;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using System;
using System.Collections.Generic;

namespace Quant
{
    /// <summary>
    /// Provides an implementation of <see cref="IAlphaModel"/> that wraps a <see cref="PyObject"/> object
    /// </summary>
    public class AlphaModelPythonWrapper : AlphaModell
    {
        private readonly dynamic _model;

        /// <summary>
        /// Defines a name for a framework model
        /// </summary>
        public override string Name
        {
            get
            {
                using (Py.GIL())
                {
                    // if the model defines a Name property then use that
                    if (_model.HasAttr("Name"))
                    {
                        return (_model.Name as PyObject).GetAndDispose<string>();
                    }

                    // if the model does not define a name property, use the python type name
                    return (_model.__class__.__name__ as PyObject).GetAndDispose<string>();
                }
            }
        }

        /// <summary>
        /// Constructor for initialising the <see cref="IAlphaModel"/> class with wrapped <see cref="PyObject"/> object
        /// </summary>
        /// <param name="model">>Model that generates alpha</param>
        public AlphaModelPythonWrapper(PyObject model)
        {
            using (Py.GIL())
            {
                foreach (var attributeName in new[] { "Update", "OnSecuritiesChanged" })
                {
                    if (!model.HasAttr(attributeName))
                    {
                        throw new NotImplementedException($"IAlphaModel.{attributeName} must be implemented. Please implement this missing method on {model.GetPythonType()}");
                    }
                }
            }
            _model = model;
        }

        /// <summary>
        /// Updates this alpha model with the latest data from the algorithm.
        /// This is called each time the algorithm receives data for subscribed securities
        /// </summary>
        /// <param name="algorithm">The algorithm instance</param>
        /// <param name="data">The new data available</param>
        /// <returns>The new insights generated</returns>
        public override IEnumerable<Insight> Update(QCAlgorithm algorithm, OrderEvent orderEvent, Slice slice)
        {
            using (Py.GIL())
            {
                var insights = _model.Update(algorithm, orderEvent, slice) as PyObject;
                var iterator = insights.GetIterator();
                foreach (PyObject insight in iterator)
                {
                    yield return insight.GetAndDispose<Insight>();
                }
                iterator.Dispose();
                insights.Dispose();
            }
        }
        
        

        /// <summary>
        /// Event fired each time the we add/remove securities from the data feed
        /// </summary>
        /// <param name="algorithm">The algorithm instance that experienced the change in securities</param>
        /// <param name="changes">The security additions and removals from the algorithm</param>
        public override void OnSecuritiesChanged(QCAlgorithm algorithm, SecurityChanges changes)
        {
            using (Py.GIL())
            {
                _model.OnSecuritiesChanged(algorithm, changes);
            }
        }
    }
}