Python Forum
Cant access variable from anywhere
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cant access variable from anywhere
#21
You've posted words, not code. Show a minimal, complete C# example that demonstrates what you're trying to do.
Reply
#22
private variable implies a class. Python has classes. Python classes are just like C# classes. Here is a Python class based on your original post.
class SomeClass:
    def __init__(self, m, s, t, y, z=0):
        self.m = m
        self.s = s
        self.t = t
        self.y = y
        self._z = z

    @property
    def z(self):
        f = (self.m - 5) / (self.m - self._z)
        sm = self.s / f
        fi = sm + self.t
        self._z = fi / self.y
        return self._z

    @z.setter
    def z(self, value):
        self._z = value

thing = SomeClass(1, 2, 3, 4)
print(thing.z, thing.z, thing.z)

thing.y = 2
thing.z = 0
print(thing.z, thing.z, thing.z)
Output:
0.625 0.703125 0.712890625 1.25 1.5625 1.640625
As you can see from the output. z changes value each time it is accessed. Also demonstrated is how you can change attributes of the object (values used in the equations) from outside the class.
Reply
#23
This the best i can come with. Its simple every loop arent nested but index, foundindex, sumvolfibo and f are connected. Main variables are declare in private on top of the class. The other variables are declared localy. This is the exact order of the script.
Reply
#24
The code you posted is not a script. It is a class. An incomplete class. No instances of the class are created, so it is never used. I'll assume that is an editing decision. Here is how I would write it in Python. There are a lot of undefined variables in you example. I don't know where they come from, so I made some of them attributes of the superclass and others arguments to a method.

I gave my class a method because without a method it isn't very useful. It runs once when initialized and that is it. I'm guessing that your code would call some method when it wants the indicator display to change.

import indicator

class MyIndicator(indicator):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.cma = 0
        self.f = 0
        self.found_index = 0
        self.sumvolfibo = 0
 
    # Are all thes undefined variables passed in or inherited or global?
    # I decided to inherit some and take otheres as arguments
    def update(self, clovol, vor, mx, tb_price, med_price, s4):
        sum1 = sum2 = 0
        for bar_index in range(self.found_index, self.chart_bars.ToIndex+1):
            sum1 += clovol  # Odd that there is a loop
            sum2 += vor
        self.cma = sum1 / sum2  # Odder that this was inside the loop

        index = 0  # Was never initialized in your code
        for bar_index in range(self.chart_bars.GetBarIdxByX(self.chart_control, self.cursor_point_x), self.chart_bars.ToIndex-tb_price):           
            if self.bars.GetMed(bar_index) < med_price:
                med_price = self.bars.GetMed(bar_index)
                index = bar_index
                         
        fi =  (mx - (3853.5)) / (mx - self.cma)

        for bar_index in range(index, self.chart_bars.ToIndex):
            vx = self.bars.Getsomething(bar_index)  # Odd that only the last value is used
        self.sumvolfibo = vx / fi
 
        for bar_index in range(index, self.chart_bars):
            if s4 >= self.sumvolfibo:
                self.found_index = bar_index
                break
Reply
#25
I need some explanation:

With python i dont get my data live, i use an excel file:
dataframe1 = pd.read_excel(r'C:\Users\faceo\Documents\NinjaTrader Grid 2022-10-26 01-30 .xlsx')
df = dataframe1
Than data are exported to a list:
v_list = []
d_list = []
cw_list = []

v_list.extend(df['Volume'].tolist())
d_list.extend(df['Close'].tolist())
cw_list.extend(df['CWMA'].tolist())
I added in init function:
self.v_list = []
self.d_list = []
self.cw_list = []
Is that correct?
I assume i should introduce in init function the df part? But how? Do i need to create a new function?

If i try to print cma inside the class like print(cma) nothing show up in the output. I dont get any error message.
When i came up with the C# example i cut a lot of corners.
The self. part are global variables that can be accessed anywhere in the class? The superclass is necessary?

TY
Reply
#26
Passing lists is probably the wrong way to do it. If you are mimicking processing live data you want to call the function multiple times, once for each row in your excel file.
import pandas as pd

# Make a dataframe containing some data
df = pd.DataFrame({column:range(20) for column in ("Volume", "Extra", "Close", "Stuff", "CWMA")})

# Iterate through the dataframe extracting values from specific columns.
for volume, close, cwma in df[["Volume", "Close", "CWMA"]].values:
    # Pass values as arguments to a function
    print(volume, close, cwma)
As for the other questions.

If you don't remember how object attributes work you should review Python classes.
I don't know if subclassing is required. You refuse to provide useful in information, so I have to guess.
If you print but see no output it means the code with the print statement is not executed,
Reply
#27
All my variables are returning 0. Where am i wrong?
Btw what i meant by printing variables inside the class is to print those who are not part of def__init__ I mean you can print a variable within a class in C#, dont seem to be the case in python: like sum1 and sum2.
Reply
#28
You have done nothing to make them not be zero. Try calling update() and see what happens. Of course someting will have to define volume and close, and you'll have to change fx, and there are probably other things I'm not seeing that still haven't been implement
Reply
#29
Output:
update <bound method MyIndicator.update of <__main__.MyIndicator object at 0x00000284A80FC370>> __main__ 35.0 3835.75 3835.75 <function MyIndicator.__init__ at 0x00000284A87B11B0> <function MyIndicator.update at 0x00000284A87B08B0> {'__module__': '__main__', 'volume': 35.0, 'close': 3835.75, 'cwma': 3835.75, '__init__': <function MyIndicator.__init__ at 0x00000284A87B11B0>, 'update': <function MyIndicator.update at 0x00000284A87B08B0>, '__dict__': <attribute '__dict__' of 'MyIndicator' objects>, '__weakref__': <attribute '__weakref__' of 'MyIndicator' objects>, '__doc__': None} <attribute '__weakref__' of 'MyIndicator' objects> None
define volume and close? if you mean: df = pd.read_excel(r'C:\Users\faceo\Documents\NinjaTrader Grid 2022-10-26 01-30 .xlsx') its already been done outside of the class. Actually i do get the data from the excel sheet inside the class.
Reply
#30
Did you remove some code from post #27? Now I have even less chance of answering your questions.

I remember there being code. I remember there being a class with a method named update. I remember the method referencing some variables that named volume and close that where were not passed into the method as arguments. Before calling the method you needed to initialize those variables. They'd have to be global variables. You already know that global variables should not be used to pass values in or out of a method/function, but yeah, sure, go ahead and make them global.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can we access instance variable of parent class in child class using inheritance akdube 3 14,027 Nov-13-2020, 03:43 AM
Last Post: SalsaBeanDip
  Access a variable of a daemon peek_no_boo 8 3,403 Apr-03-2020, 07:29 PM
Last Post: BrendanD
  How to access class variable? instances vs class drSlump 5 3,383 Dec-11-2019, 06:26 PM
Last Post: Gribouillis
  How can I access this variable from a def? student3m 1 2,955 Sep-23-2017, 02:06 PM
Last Post: ichabod801
  Can access class private variable? Michael 2 7,207 Aug-11-2017, 01:59 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020