Overall Statistics
//  The Goal of this strategy is simply to learn the mechanics of QuantConnect
//  price targets, and limit orders.


using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Indicators;

namespace QuantConnect.Algorithm.CSharp
{
    public class LearningLimits : QCAlgorithm
    {
        decimal limitPct = 0.99999m;
        
  		bool OrderSubmitted = false;
  		bool ExitOrderSubmitted = false;
  		
  		string ticker = "BTCUSD";
        decimal ProfitPct = .05m;
        decimal LossPct = -.05m;
        
        DateTime TimeofEntry;

        public override void Initialize()
        {
            SetStartDate(2018,1,01);  // Set Start Date
            SetEndDate(DateTime.Now);    // Set End Date
            SetCash(100000);          // Set Strategy Cash

            AddCrypto(ticker, Resolution.Minute);
        }

        public override void OnData(Slice data)
        {
 

            if (!Portfolio.Invested && OrderSubmitted == false)  
            {
            	decimal LimitPrice = Decimal.Multiply(Securities[ticker].Price, limitPct);
            	decimal LimitPrice2 = decimal.Round(LimitPrice, 2);
            	
                LimitOrder(ticker, 1, LimitPrice2, "Filled on " + ticker + " at " + LimitPrice2);
                OrderSubmitted = true;
                ExitOrderSubmitted = false;
                TimeofEntry = Time;
            }
            
            if (!Portfolio.Invested && ExitOrderSubmitted == false && (Time - TimeofEntry >= TimeSpan.FromDays(1)))
            {
            	Transactions.CancelOpenOrders(ticker);
            	Log("Was never filled");
            	OrderSubmitted = false;
            }

            if (Portfolio.Invested && Portfolio[ticker].UnrealizedProfitPercent > ProfitPct && ExitOrderSubmitted == false)  
            {
            	decimal LockedPrice = Portfolio[ticker].Price;
            	decimal ExitLimitPrice = Decimal.Multiply(LockedPrice,.99999m);
            	
            	StopLimitOrder(ticker, -Portfolio[ticker].Quantity, LockedPrice, ExitLimitPrice, "Take Profit order triggered for " + ticker + " at " + ExitLimitPrice);
            	ExitOrderSubmitted = true;
            	OrderSubmitted = false;
            }
            
            if (Portfolio.Invested && Portfolio[ticker].UnrealizedProfitPercent < LossPct && ExitOrderSubmitted == false)
            {
            	decimal LossLockedPrice = Portfolio[ticker].Price;
            	decimal LossLockedLimit = Portfolio[ticker].Price + Decimal.Multiply(LossPct, Portfolio[ticker].Price);
            	
            	StopLimitOrder(ticker, -Portfolio[ticker].Quantity, LossLockedPrice, LossLockedLimit, "Stop Loss order triggered for " + ticker + " at " + LossLockedLimit);
            	ExitOrderSubmitted = true;
            	OrderSubmitted = false;
            }
           
        }
    }
}