Overall Statistics
from QuantConnect.Data import SubscriptionDataSource
from QuantConnect.Python import PythonData
from datetime import date, timedelta, datetime
from decimal import Decimal

class importCustomDataExample(QCAlgorithm):

    def Initialize(self):
        '''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

        self.SetStartDate(2017,1, 10)  #Set Start Date
        self.SetEndDate(2018,12,31)    #Set End Date
        self.SetCash(10000)           #Set Strategy Cash

        # Add custom data to security universe
        self.AddData(predEURUSD, "predEURUSD", Resolution.Hour)
        # Add EUR/USD currency pair to security universe
        self.AddForex("EURUSD", Resolution.Hour, Market.Oanda)

    def OnData(self, data):
        if not data.ContainsKey("predEURUSD") or not data.ContainsKey("EURUSD"): return
        
        # Retrieve High Ask Price from object
        highASK=data["predEURUSD"].Value
        quoteBar = data['EURUSD']
        
        # User variables
        highASKOpendiff = highASK- quoteBar.Open
        BuyTPASK=Decimal(highASKOpendiff*0.8)
        BuySLASK=highASKOpendiff*2

        # Buy currency pair
        if not self.Portfolio.Invested and highASKOpendiff > 0.0030:
            self.Buy("EURUSD", 100)
            
            averageFillPrice = self.Portfolio["EURUSD"].AveragePrice
            
            # Use average fill price to determine stop-loss and take-profit price level
            self.LimitOrder("EURUSD", -100, (averageFillPrice + BuyTPASK))
            self.StopMarketOrder("EURUSD", -100, (averageFillPrice -BuySLASK))
        
    ### Cancel remaining order if limit order or stop loss order is executed
    def OnOrderEvent(self, orderEvent):
        order = self.Transactions.GetOrderById(orderEvent.OrderId)
        
        if order.Status == OrderStatus.Filled:
            if order.Type == OrderType.Limit or order.Type == OrderType.Limit:
                self.Transactions.CancelOpenOrders(order.Symbol)
                
        if order.Status == OrderStatus.Canceled:
            self.Log(str(orderEvent))


class predEURUSD(PythonData):
    "Import custom data from a csv file"
    def GetSource(self, config, date, isLiveMode):
        return SubscriptionDataSource("http://sensedrive.science/files/EURUSD1H_CHL_ASK_cat.csv", SubscriptionTransportMedium.RemoteFile)
    def Reader(self, config, line, date, isLiveMode):
        if not (line.strip() and line[0].isdigit()): return None
        index = predEURUSD()
        index.Symbol = config.Symbol
        try:
            data = line.split(',')

            index.Time = datetime.strptime(data[0], "%Y-%m-%d %H:%M:%S")
            
            ### Retrieve "predicted" High Ask Price
            index.Value = Decimal(data[2])
            
        except:
            return None
        return index