Overall Statistics
Total Trades
83
Average Win
0.08%
Average Loss
-1.17%
Compounding Annual Return
-1.086%
Drawdown
2.800%
Expectancy
-0.039
Net Profit
-2.134%
Sharpe Ratio
-0.615
Loss Rate
10%
Win Rate
90%
Profit-Loss Ratio
0.06
Alpha
0.111
Beta
-8.569
Annual Standard Deviation
0.012
Annual Variance
0
Information Ratio
-1.75
Tracking Error
0.012
Treynor Ratio
0.001
Total Fees
$0.00
import numpy as np
import pandas as pd
from QuantConnect.Data import SubscriptionDataSource
from QuantConnect.Python import PythonData
from datetime import date, timedelta, datetime
from decimal import Decimal
import math
import calendar

### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
class BasicTemplateAlgorithm(QCAlgorithm):
    '''Basic template algorithm simply initializes the date range and cash'''

    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
        # Find more symbols here: http://quantconnect.com/data
        #self.AddEquity("SPY",Resolution.Minute)
        self.AddForex("EURUSD", Resolution.Minute, Market.Oanda)
        self.AddData(predEURUSDASK, "predEURUSDASK", Resolution.Hour, fillforward=True)
        self.AddData(predEURUSDBID, "predEURUSDBID", Resolution.Hour, fillforward=True)
        self.SetTimeZone("Etc/GMT0")
        self.Debug("Everything loaded")
        self.risk = 0.2
        
        self.Securities["EURUSD"].SetLeverage(500)
                           
        self.last_hour = 0

    def OnData(self, data):
        if (data.ContainsKey("predEURUSDASK") or data.ContainsKey("predEURUSDBID")) and data.ContainsKey("EURUSD"):
            if self.last_hour == data["EURUSD"].Time.hour:
                return
            else:
                self.last_hour = data["EURUSD"].Time.hour
                quoteBar = data["EURUSD"]
                self.Log(f"Time: {quoteBar.EndTime}") #The time the period closes
                self.Log(f"Open: {quoteBar.Open}")
                # Retrieve High Ask Price from object
                highASK=data["predEURUSDASK"].Value
                self.Log(f"High ASK: {highASK}")
                # User variables
                highASKOpendiff = highASK- quoteBar.Open
                self.Log(f"highASKOpendiff: {highASKOpendiff}")
                BuyTPASK=highASKOpendiff*1
                self.Log(f"BuyTPASK: {BuyTPASK}")
                BuySLASK=highASKOpendiff*10
                self.Log(f"BuySLASK: {BuySLASK}")
                # Retrieve Low Bid Price from object
                lowBID=data["predEURUSDBID"].Value
                self.Log(f"Low BID: {lowBID}")
                # User variables
                OpenLowBIDdiff = quoteBar.Open - lowBID
                self.Log(f"OpenLowBIDdiff: {OpenLowBIDdiff}")
                SellTPBID=OpenLowBIDdiff*1
                self.Log(f"SellTPBID: {SellTPBID}")
                SellSLBID=OpenLowBIDdiff*10
                self.Log(f"SellSLBID: {SellSLBID}")
                qty = math.floor(self.Portfolio.Cash * self.risk/self.Securities["EURUSD"].Price) #MarginRemaining
                if highASKOpendiff >= OpenLowBIDdiff:
                    if not self.Portfolio.Invested:
                        self.Buy("EURUSD", qty)   # every hour
                        #Approach 1: self.SetHolding("EURUSD",0.2)
                        averageFillPrice = self.Portfolio["EURUSD"].AveragePrice
                        self.LimitOrder("EURUSD", -qty, (averageFillPrice +BuyTPASK))
                        self.StopMarketOrder("EURUSD", -qty, (averageFillPrice -BuySLASK))
                else:
                    if not self.Portfolio.Invested:
                        self.Sell("EURUSD", qty)
                        averageFillPrice = self.Portfolio["EURUSD"].AveragePrice
                        self.LimitOrder("EURUSD", qty, (averageFillPrice -SellTPBID))
                        self.StopMarketOrder("EURUSD", qty, (averageFillPrice + SellSLBID))
                #else:
                    #return
        
    def OnOrderEvent(self, orderEvent):
        order = self.Transactions.GetOrderById(orderEvent.OrderId)
        
        if order.Status == OrderStatus.Filled:
            if order.Type == OrderType.Limit or order.Type == OrderType.StopMarket:
                self.Transactions.CancelOpenOrders(order.Symbol)
                
        if order.Status == OrderStatus.Canceled:
            self.Log(str(orderEvent))
    
    def EveryHour(self):
        pass
    
    
class predEURUSDASK(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 = predEURUSDASK()
        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          
        
class predEURUSDBID(PythonData):
    #"Import custom data from a csv file"
    def GetSource(self, config, date, isLiveMode):
        #Changed BID -> ASK
        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 = predEURUSDBID()
        index.Symbol = config.Symbol
        try:
            data = line.split(',')

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