Ejemplo n.º 1
0
def test_correct_overload_selection():
    """Test correct overloading selection for common types."""
    from System import (String, Double, Single,
                        Int16, Int32, Int64)
    from System import Math

    substr = String("substring")
    assert substr.Substring(2) == substr.Substring.__overloads__[Int32](
        Int32(2))
    assert substr.Substring(2, 3) == substr.Substring.__overloads__[Int32, Int32](
        Int32(2), Int32(3))

    for atype, value1, value2 in zip([Double, Single, Int16, Int32, Int64],
                                     [1.0, 1.0, 1, 1, 1],
                                     [2.0, 0.5, 2, 0, -1]):
        assert Math.Abs(atype(value1)) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Abs(value1) == Math.Abs.__overloads__[atype](atype(value1))
        assert Math.Max(atype(value1),
                        atype(value2)) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))
        assert Math.Max(atype(value1),
                        value2) == Math.Max.__overloads__[atype, atype](
            atype(value1), atype(value2))

    clr.AddReference("System.Runtime.InteropServices")
    from System.Runtime.InteropServices import GCHandle, GCHandleType
    from System import Array, Byte
    cs_array = Array.CreateInstance(Byte, 1000)
    handler = GCHandle.Alloc(cs_array, GCHandleType.Pinned)
Ejemplo n.º 2
0
def onTick(timer, e):
	global ts

	ts = ts.Add(timer.Interval)
	entry = Entry()
	
	if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
		entry.Title = String.Format("予定の{0}分前になりました", Math.Abs(ts.Minutes).ToString())
	else:
		if Math.Abs(ts.Minutes) == 1:
			entry.Title = String.Format("{0} minute remaining", Math.Abs(ts.Minutes).ToString())
		else:
			entry.Title = String.Format("{0} minutes remaining", Math.Abs(ts.Minutes).ToString())

	if ts.TotalMilliseconds >= 0:
		timer.Stop()
		ts = TimeSpan.Zero

		if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
			entry.Title = "予定の時間になりました"
		else:
			entry.Title= "Time expired"

	entryList = List[Entry]()
	entryList.Add(entry)
	Script.Instance.Alert(entryList)
Ejemplo n.º 3
0
 def run_thread():
     for i in range(10):
         time.sleep(0.1)
         dprint("thread %s %d" % (thread.get_ident(), i))
         mstr = String("thread %s %d" % (thread.get_ident(), i))
         pstr = mstr.ToString()
         done.append(None)
         dprint("thread %s %d done" % (thread.get_ident(), i))
Ejemplo n.º 4
0
 def inList(self, myString, myVal, caseInsensitive=True):
     if caseInsensitive == True:
         myString = str.lower(myString)
         myVal = str.lower(myVal)
     theVals = myVal.strip(',').split(',')
     for word in theVals:
         if String.Trim(word) == String.Trim(myString): return True
     return False
Ejemplo n.º 5
0
def SearchTracks(composer):
    WriteLine(String.Format("Searching for tracks by '{0}'...", composer))
    tracks = GetAllTracks().Where(lambda t: t.Composer == composer)
    WriteLine(
        String.Format("Found {0} tracks by '{1}'", tracks.Count(), composer))
    for t in tracks:
        WriteLine(String.Format("Track Id: {0} Name: {1}", t.Id, t.Name))
    WriteLine("Search complete")
Ejemplo n.º 6
0
    def onUpdate():
        if NetworkInterface.GetIsNetworkAvailable():
            try:
                response = None
                stream = None

                try:
                    response = request.GetResponse()
                    stream = response.GetResponseStream()
                    doc = XmlDocument()
                    doc.Load(stream)

                    for itemXmlNode in doc.GetElementsByTagName("item"):
                        entry = Entry()
                        epicenter = None
                        maxLevel = None

                        for xmlNode in itemXmlNode.ChildNodes:
                            if xmlNode.Name.Equals("link"):
                                entry.Resource = Uri(xmlNode.InnerText)
                            elif xmlNode.Name.Equals("description"):
                                entry.Description = xmlNode.InnerText
                            elif xmlNode.Name.Equals("tenkiJP:earthquake"):
                                for attribute in xmlNode.Attributes:
                                    if attribute.Name.Equals("epicenter"):
                                        epicenter = attribute.Value
                                    elif attribute.Name.Equals("max_level"):
                                        maxLevel = attribute.Value
                                    elif attribute.Name.Equals(
                                            "outbreak_datetime"):
                                        entry.Created = entry.Modified = DateTime.Parse(
                                            attribute.Value)

                        if epicenter is not None:
                            if String.IsNullOrEmpty(maxLevel):
                                maxLevel = "N/A"

                            if CultureInfo.CurrentCulture.Equals(
                                    CultureInfo.GetCultureInfo("ja-JP")):
                                entry.Title = String.Format(
                                    "震度{0} - {1}", maxLevel, epicenter)
                            else:
                                entry.Title = String.Format(
                                    "Intensity {0} - {1}", maxLevel, epicenter)

                            entryList.Add(entry)

                finally:
                    if stream is not None:
                        stream.Close()

                    if response is not None:
                        response.Close()

            except Exception, e:
                Trace.WriteLine(e.clsException.Message)
                Trace.WriteLine(e.clsException.StackTrace)
Ejemplo n.º 7
0
def print_maximum_capabilities(setting):
    # Get Max Capabilities
    print(String.Format("{0} {1} {2}", "Maximum", setting, "Capabilities:"))

    for item in experiment.GetMaximumCapabilities(setting):
        if (setting == CameraSettings.AdcSpeed):
            print_speeds(item)
        else:
            print(String.Format('\t{0} {1}', setting, item))
Ejemplo n.º 8
0
def onTick(timer, e):
    global username, password

    if not String.IsNullOrEmpty(username) and not String.IsNullOrEmpty(
            password):
        update()

    timer.Stop()
    timer.Interval = TimeSpan.FromMinutes(5)
    timer.Start()
Ejemplo n.º 9
0
def getTermList(dictionary, text):
    stringBuilder = StringBuilder(text)
    selectedTermList = List[String]()

    while stringBuilder.Length > 0:
        s1 = stringBuilder.ToString()
        selectedTerm1 = None

        if dictionary.ContainsKey(s1[0]):
            for term in dictionary[s1[0]]:
                if s1.StartsWith(term,
                                 StringComparison.Ordinal) and term.Length > (
                                     0 if selectedTerm1 is None else
                                     selectedTerm1.Length):
                    selectedTerm1 = term

        if String.IsNullOrEmpty(selectedTerm1):
            stringBuilder.Remove(0, 1)
        else:
            sb = StringBuilder(
                stringBuilder.ToString(1, stringBuilder.Length - 1))
            selectedTerm2 = None
            i = 0
            max = 0

            while sb.Length > 0 and i < selectedTerm1.Length:
                s2 = sb.ToString()

                if dictionary.ContainsKey(s2[0]):
                    for term in dictionary[s2[0]]:
                        if s2.StartsWith(
                                term, StringComparison.Ordinal
                        ) and term.Length > (0 if selectedTerm2 is None else
                                             selectedTerm2.Length):
                            selectedTerm2 = term
                            max = i + selectedTerm2.Length

                sb.Remove(0, 1)
                i += 1

            if not String.IsNullOrEmpty(
                    selectedTerm2
            ) and selectedTerm1.Length < selectedTerm2.Length:
                if not selectedTermList.Contains(selectedTerm2):
                    selectedTermList.Add(selectedTerm2)

                stringBuilder.Remove(0, max)

            else:
                if not selectedTermList.Contains(selectedTerm1):
                    selectedTermList.Add(selectedTerm1)

                stringBuilder.Remove(0, selectedTerm1.Length)

    return selectedTermList
Ejemplo n.º 10
0
def get_spectrometer_info():
    print(
        String.Format(
            "{0} {1}", "Center Wave Length:",
            str(
                experiment.GetValue(
                    SpectrometerSettings.GratingCenterWavelength))))

    print(
        String.Format("{0} {1}", "Grating:",
                      str(experiment.GetValue(SpectrometerSettings.Grating))))
Ejemplo n.º 11
0
def multiValueRemove(myList, myVal, caseinsensitive=True):
    myVal = String.Trim(str(myVal))
    theList = myList.strip(',').split(',')
    newList = []
    for l in theList:
        l = String.Trim(l)
        if caseinsensitive:
            if l.lower() <> myVal.lower(): newList.Add(l)
        else:
            if l <> myVal: newList.Add(l)
    return ','.join(newList)
Ejemplo n.º 12
0
    def groupHeaders(self, theFile=globalvars.DATFILE):
        '''
		returns a list of group headers in the rule set
		'''
        headers = []
        if File.Exists(theFile):
            s1 = File.ReadAllLines(theFile)
            s1 = [line for line in s1 if String.StartsWith(line, '#@ GROUP')]
            for line in s1:
                headers.Add(String.Replace(line, '#@ GROUP ', ''))

        return headers
Ejemplo n.º 13
0
def multiValueReplace(myList, oldVal, myVal, caseinsensitive=True):
    oldVal = String.Trim(str(oldVal))
    myVal = String.Trim(str(myVal))
    newList = []
    theList = myList.strip(',').split(',')
    for l in theList:
        l = String.Trim(l)
        if caseinsensitive == True:
            if l.lower() == oldVal.lower(): l = myVal
        else:
            if l == oldVal: l = myVal
        if newList.count(l) == 0:
            newList.Add(l)
    return ','.join(newList)
Ejemplo n.º 14
0
 def get_spectrometer_info(self, *args):
     logger.debug('Called get_spectrometer_info directly! Args: ' +
                  str(args))
     print(
         String.Format(
             "{0} {1}", "Center Wave Length:",
             str(
                 self.experiment.GetValue(
                     SpectrometerSettings.GratingCenterWavelength))))
     print(
         String.Format(
             "{0} {1}", "Grating:",
             str(self.experiment.GetValue(SpectrometerSettings.Grating))))
     return "Function Completed"
Ejemplo n.º 15
0
    def test_pythonnet(self):
        fLOG(__file__,
             self._testMethodName,
             OutputPrint=__name__ == "__main__")
        if sys.platform.startswith("win"):
            from src.ensae_teaching_cs.pythonnet import clr
            from System import String
            s = String("example")
            x = s.Replace("e", "j")
            assert "jxamplj" == x

            from System.Collections.Generic import Dictionary
            d = Dictionary[String, String]()
            d["un"] = "1"
            assert d.Count == 1
Ejemplo n.º 16
0
def TestInvoices():
    WriteLine("Testing Invoices...")
    invoice = GetAllInvoices().FirstOrDefault()
    WriteLine(
        String.Format("Invoice Id: {0} Date: {1}", invoice.Id,
                      invoice.InvoiceDate))
    lines = invoice.Lines
    WriteLine(String.Format("Found {0} tracks", lines.Count))
    for l in lines:
        WriteLine(
            String.Format(
                "Invoice Line Id: {0} Track Id: {1} Track Name: {2} Price: {3}",
                l.Id, l.Track.Id, l.Track.Name, l.Track.UnitPrice))
    WriteLine("Testing Invoices complete")
    WriteLine()
Ejemplo n.º 17
0
    def validate(self, s):
        '''
		validates the current line in the configuration for basic syntax errors
		if everything ok it returns the line
		else it returns the line prefixed with '# invalid expression'
	
		'''
        s = String.Trim(s)
        if not len(s) > 0:
            self.err = False
        # check if line is comment
        if s.StartsWith('#@'):  # directive?
            self.err = False
            return
        if s.StartsWith('#'):  # comment?
            self.err = False
            return
        if s.StartsWith('<<'):  # valid rule
            if not String.EndsWith(s, '>>'):
                self.err = True
                self.error = 'missing >> at the end of rule'
                return
            if str.count(s, '=>') == 0:
                self.err = True
                self.error = 'missing => in rule'
                return
            if str.count(s, '=>') > 1:
                self.err = True
                self.error = 'more than one occurence of => in rule'
                return
            if str.count(s, '<<') <> str.count(s, '>>'):
                self.err = True
                self.error = 'count of << mismatches count of >>'
                return
            if str.count(s, '<<') > str.count(s, ':'):
                self.err = True
                self.error = 'count of << mismatches count of :'
                return
            else:
                self.err = False
                self.error = ''
                return
        else:  # rule does not start with <<
            self.err = True
            self.error = 'rules must start with <<'
            return

        return
Ejemplo n.º 18
0
        def parseOutline(m, n):
            if not n.HasChildNodes:
                return None

            for xmlNode in n.ChildNodes:
                if xmlNode.Name.Equals("outline"):
                    text = None
                    xmlUrl = None
                    htmlUrl = None

                    for xmlAttribute in xmlNode.Attributes:
                        if xmlAttribute.Name.Equals(
                                "title") or xmlAttribute.Name.Equals("text"):
                            text = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("xmlUrl"):
                            xmlUrl = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("htmlUrl"):
                            htmlUrl = xmlAttribute.Value

                    if not String.IsNullOrEmpty(text):
                        if String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()
                            mi.Header = text

                            parsedMenuItem = parseOutline(mi, xmlNode)

                            if parsedMenuItem is None:
                                m.Items.Add(mi)
                            else:
                                m.Items.Add(parsedMenuItem)
                        elif not String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()

                            def onClick(sender, args):
                                if not String.IsNullOrEmpty(sender.Tag):

                                    def onStart(state):
                                        Process.Start(state)

                                    Task.Factory.StartNew(onStart, sender.Tag)

                            mi.Header = text
                            mi.Click += onClick
                            mi.Tag = htmlUrl

                            m.Items.Add(mi)

            return m
Ejemplo n.º 19
0
def timeUpdate(timeFrame):
    global macd
    global macdPrev
    global signalPrev
    if Factory.Debug:
        print "Update from Python"
        if Base.InPosition:
            Factory.Display.appendLine("Update for {0}, in position", Pair)

    lMacd = Base.getMACDasList(TimeFrame.m5, PriceComponent.BidClose, 12, 26, 9)
    print lMacd
    macd = lMacd[0]
    signal = lMacd[1]
    history = lMacd[2]
    Base.Log.debug(
        String.format(
            "timeUpdate({0}):{1}, macd={2}, signal={3}", Base.Factory.TimeFrameMap[timeFrame], Pair, macd, signal
        )
    )

    if macd < signal and macdPrev > signalPrev:
        Factory.Display.appendLine("SELL " + Pair)
        Base.Log.debug("SELL " + Pair)
    elif macd > signal and macdPrev < signalPrev:
        Factory.Display.appendLine("BUY " + Pair)
        Base.Log.debug("BUY " + Pair)

    macdPrev = macd
    signalPrev = signal
Ejemplo n.º 20
0
def get_image_data(file):
    # Get the first frame
    imageData = file.GetFrame(0, 0)

    # Print Height and Width of first frame
    print(
        String.Format('\t{0} {1}X{2}', "Image Width and Height:",
                      imageData.Width, imageData.Height))

    # Get image data
    buffer = imageData.GetData()

    # Print first 10 pixel intensities
    for pixel in range(0, 10):
        print(
            String.Format('\t{0} {1}', 'Pixel Intensity:', str(buffer[pixel])))
Ejemplo n.º 21
0
def PowerShellExecute(PowerShellCode,
                      OutString=True,
                      BypassLogging=True,
                      BypassAmsi=True):
    with PowerShell.Create() as ps:
        flags = BindingFlags.NonPublic | BindingFlags.Static
        if BypassLogging:
            PSEtwLogProvider = ps.GetType().Assembly.GetType(
                "System.Management.Automation.Tracing.PSEtwLogProvider")
            if PSEtwLogProvider is not None:
                EtwProvider = PSEtwLogProvider.GetField("etwProvider", flags)
                #EventProvider = Eventing.EventProvider(Guid.NewGuid())
                #EtwProvider.SetValue(None, EventProvider)

        if BypassAmsi:
            amsiUtils = ps.GetType().Assembly.GetType(
                "System.Management.Automation.AmsiUtils")
            if amsiUtils is not None:
                amsiUtils.GetField("amsiInitFailed",
                                   flags).SetValue(None, True)

        ps.AddScript(PowerShellCode)
        if OutString:
            ps.AddCommand("Out-String")
        results = ps.Invoke()
        output = String.Join(Environment.NewLine, results)
        ps.Commands.Clear()
        return output
Ejemplo n.º 22
0
				def onUpdate():
					shortenedUri = None

					if NetworkInterface.GetIsNetworkAvailable():
						try:
							request = WebRequest.Create(Uri(String.Concat("http://nazr.in/api/shorten.json?url=", urlEncode(uri.ToString()))))
							response = None
							stream = None
							streamReader = None

							try:
								response = request.GetResponse()
								stream = response.GetResponseStream()
								streamReader = StreamReader(stream)
								jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd())

								if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("url"):
									shortenedUri = Uri(jsonDictionary["url"])

							finally:
								if streamReader is not None:
									streamReader.Close()

								if stream is not None:
									stream.Close()
			
								if response is not None:
									response.Close()

						except Exception, e:
							Trace.WriteLine(e.clsException.Message)
							Trace.WriteLine(e.clsException.StackTrace)
Ejemplo n.º 23
0
    def write(self, theText):
        '''
		writes the context of the configurator window to a file
		returns ERROR constant (NOERROR if successful)
		if the parser made any alterations the editedByParser property will be
		set to True
		'''
        self.editedByParser = False
        theText = unicode(theText)
        s = String.Split(theText, '\n')
        # s = str.split(str(theText),'\n')
        tmp = str('')
        errlines = 0
        myParser = parser()
        pre = ''

        s = [line for line in s if str.Trim(line) <> '']

        for line in s:
            myParser.validate(unicode(line))
            if myParser.err:
                pre = myParser.commentedLine(line)
                errlines += 1
                self.editedByParser = True
            else:
                pre = unicode(line)
            tmp += '%s%s' % (pre, System.Environment.NewLine)
        if len(tmp) > 0:
            try:
                File.WriteAllText(self.theFile, tmp)
            except Exception, err:
                return self.ERRORSAVEFILE
Ejemplo n.º 24
0
def print_setting(setting):
    # Check for existence before
    # getting gain, adc rate, or adc quality
    if experiment.Exists(setting):
        print(
            String.Format('{0} {1} = {2}', "\tReading ", str(setting),
                          experiment.GetValue(setting)))
Ejemplo n.º 25
0
def print_current_capabilities(setting):
    # Get current ADC rates that correspond
    # with the current quality setting
    print(String.Format("{0} {1} {2}", "Current", setting, "Capabilities:"))

    for item in experiment.GetCurrentCapabilities(setting):
        print_speeds(item)
Ejemplo n.º 26
0
def print_strings(is_64_bits=False):

    strings = []

    print '[+] Importing System.String'
    import clr
    clr.AddReference('System')
    from System import String
    
    clr.AddReference('ObjectUtils')
    from ObjectUtils import Objects, Heap
    
    test_str = String('DEADBEEF')
    test_str_ptr    = Objects.GetObjectAddress(test_str)
    test_str_mt     = Objects.GetMTAddress(test_str_ptr)
    test_str_type   = Objects.GetTypeByName('System.String')
    
    for heap in ishtar.MANAGED_HEAPS:
        print 'Parsing heap: {2}; {0} - {1}'.format(*heap)
        
        heap_start = heap[0]
        heap_end = heap[1]
        heap_name = heap[2]
        
        if is_64_bits:
            strings.extend(Heap.FindObjectsByMTAddress64(heap_start, heap_end, test_str_mt, test_str_type))
        else:
            strings.extend(Heap.FindObjectsByMTAddress32(heap_start, heap_end, test_str_mt, test_str_type))
        
        
    print '[+] Done.'
    return strings
Ejemplo n.º 27
0
def set_value(setting, value):
    # Check for existence before setting
    # gain, adc rate, or adc quality
    if experiment.Exists(setting):
        print(String.Format("{0}{1} to {2}", "Setting ", setting, value))

        experiment.SetValue(setting, value)
Ejemplo n.º 28
0
                            def onClick(sender, args):
                                if not String.IsNullOrEmpty(sender.Tag):

                                    def onStart(state):
                                        Process.Start(state)

                                    Task.Factory.StartNew(onStart, sender.Tag)
Ejemplo n.º 29
0
    def __setattr__(self, key, value):
        try:
            _type = self.get_type(key)
        except AttributeError:
            raise AttributeError(f"{key} is not a valid field of {self.db_name}")

        if not self.assignment_types_are_equal(_type, value):
            raise Exception(f"Trying to assign incorrect type to {key}")

        default_arguments = (self.data, getattr(self.api, key.upper()))

        error = None
        if _type == self.api.ADK_FIELD_TYPE.eChar:
            error = self.api.AdkSetStr(*default_arguments, String(f"{value}"))[0]
        elif _type == self.api.ADK_FIELD_TYPE.eDouble:
            error = self.api.AdkSetDouble(*default_arguments, Double(value))
        elif _type == self.api.ADK_FIELD_TYPE.eBool:
            error = self.api.AdkSetBool(*default_arguments, Boolean(value))
        elif _type == self.api.ADK_FIELD_TYPE.eDate:
            error = self.api.AdkSetDate(*default_arguments, self.to_date(value))

        if error and error.lRc != self.api.ADKE_OK:
            error_message = self.api.AdkGetErrorText(
                error, self.api.ADK_ERROR_TEXT_TYPE.elRc
            )
            raise Exception(error_message)
Ejemplo n.º 30
0
def CalculateMassPrecision(rawFile, scanNumber: int):

    # Get the scan from the RAW file
    scan = Scan.FromFile(rawFile, scanNumber)

    # Get the scan event and from the scan event get the analyzer type for this scan
    scanEvent = rawFile.GetScanEventForScanNumber(scanNumber)

    scanFilter = rawFile.GetFilterForScanNumber(scanNumber)

    print(scanFilter.MassAnalyzer)
    print(scanEvent)

    # Get the trailer extra data to get the ion time for this file
    logEntry = rawFile.GetTrailerExtraInformation(scanNumber)

    print(logEntry.Labels)

    trailerHeadings = List[String]()
    trailerValues = List[String]()
    for i in range(logEntry.Length):

        trailerHeadings.Add(String(logEntry.Labels[i]))
        trailerValues.Add(String(logEntry.Values[i]))

    # create the mass precision estimate object
    precisionEstimate = PrecisionEstimate()

    # Get the ion time from the trailer extra data values
    ionTime = precisionEstimate.GetIonTime(scanFilter.MassAnalyzer, scan,
                                           trailerHeadings, trailerValues)

    # Calculate the mass precision for the scan
    listResults = precisionEstimate.GetMassPrecisionEstimate(
        scan, scanFilter.MassAnalyzer, ionTime,
        rawFile.RunHeader.MassResolution)

    # Output the mass precision results
    if len(listResults) > 0:

        print("Mass Precision Results:")

        for result in listResults:

            print("Mass {}, mmu = {}, ppm = {}".format(
                result.Mass, result.MassAccuracyInMmu,
                result.MassAccuracyInPpm))
Ejemplo n.º 31
0
 def On_PlayerConnected(self, player):
     Server.Broadcast(player.Name + " has joined the server!")
     player.Message(
         String.Format("This server is working with Pluton[{0}]",
                       Pluton.Bootstrap.Version))
     player.Message("Type /help for a list of commands")
     player.Inventory.Add(6604, 40)
     player.Inventory.Add(11963, 1)
Ejemplo n.º 32
0
def timeUpdate(timeFrame):
	global macdShort
	global macdPrev
	global signalPrev
	global macdLong
	global macdSignal
	global emaPeriods
	global amount
	global stopPips
	global limitPips
			
	lMacd = Base.getMACDasList(timeFrame, PriceComponent.BidClose, macdShort, macdLong, macdSignal)
	macd = lMacd[0]
	signal = lMacd[1]
	history = lMacd[2]
	Base.Log.debug(String.format("timeUpdate({0}):{1}, macd={2}, signal={3}",Base.Factory.TimeFrameMap[timeFrame], Pair,macd,signal))
	
	lastBid = Base.getLast(timeFrame, PriceComponent.BidClose)
	lastAsk = Base.getLast(timeFrame, PriceComponent.AskClose)
	ema = Base.getEMA(timeFrame, PriceComponent.BidClose, emaPeriods)


	if (not Base.InPosition
	and  ema > 0):

		if (macd < signal 
		and macdPrev > signalPrev
		and  macd > 0
		and signal > 0
		and lastBid < ema):
			entry = "SELL";
			Factory.Display.appendLine(String.Format("Open, {0}, {1}, price={2}", entry, Pair, lastBid))
			Base.enterPosition(entry, amount, lastBid, stopPips, limitPips)

		elif (macd > signal
		and macdPrev < signalPrev
		and  macd > 0
		and signal > 0
		and lastAsk > ema):
			entry = "BUY";
			Factory.Display.appendLine(String.Format("Open, {0}, {1}, price={2}", entry, Pair, lastAsk))
			Base.enterPosition(entry, amount, lastAsk, stopPips, limitPips)
		
	macdPrev = macd
	signalPrev = signal