I import technicals.py into bot.py and want to reuse the variable sl and tp from the class instance process_candles.
If a constant number is given to sl and tp in bot.py, the script is able to work. However, the desired result is to get variable sl and tp which is calculated in the class instance process_candles. from technicals.py.
snippet technicals.py as below:
df['PAIR'] = self.pair
decision = NONE
tp = 0
sl = 0
if c[-2]>o[-2]:
if ca[-1]>h[-2]+0.0010:
decision = BUY
tp = ca[-1]+0.010
sl = l[-2]-0.010
elif o[-2]>c[-2]:
if cb[-1]<l[-2]-0.0010:
decision = SELL
tp = cb[-1]-0.010
sl = h[-2]+0.010
else:
decision = NONE
snippet bot.py
def process_pairs(self):
trades_to_make = []
for pair in self.trade_pairs:
if self.timings[pair].ready == True:
self.log_message(f"Ready to trade {pair}")
techs = Technicals(self.settings[pair], self.api, pair, GRANULARITY, log=self.tech_log)
decision = techs.get_trade_decision(self.timings[pair].last_candle)
print ("process decision")
print (decision)
units = decision * self.settings[pair].units
#tp = "154"
#sl = "153"
if units != 0:
trades_to_make.append({'pair': pair, 'units': units,'take_profit':tp, 'stop_loss':sl})
Full script are as below:
technicals.py
import pandas as pd
import numpy as np
from defs import BUY, SELL, NONE
class Technicals():
def __init__(self, settings, api, pair, granularity, log=None):
self.settings = settings
self.log = log
self.api = api
self.pair = pair
self.granularity = granularity
def log_message(self, msg):
if self.log is not None:
self.log.logger.debug(msg)
def fetch_candles(self, row_count, candle_time):
status_code, df = self.api.fetch_candles(self.pair, count=row_count, granularity=self.granularity)
if df is None:
self.log_message(f"Error fetching candles for pair:{self.pair} {candle_time}, df None")
return None
elif df.iloc[-1].time != candle_time:
self.log_message(f"Error fetching candles for pair:{self.pair} {candle_time} vs {df.iloc[-1].time}")
return None
else:
return df
def process_candles(self, df):
open = df.mid_o
o = np.array(open,dtype='float')
#print (o)
high = df.mid_h
h = np.array(high,dtype='float')
#print (h)
low = df.mid_l
l = np.array(low,dtype='float')
#print (l)
close = df.mid_c
c = np.array(close,dtype='float')
print (c)
close_ask = df.ask_c
ca = np.array(close_ask,dtype='float')
print (ca)
close_bid = df.bid_c
cb = np.array(close_bid,dtype='float')
print (cb)
df['PAIR'] = self.pair
decision = NONE
tp = 0
sl = 0
if c[-2]>o[-2]:
if ca[-1]>h[-2]+0.0010:
decision = BUY
tp = ca[-1]+0.010
sl = l[-2]-0.010
elif o[-2]>c[-2]:
if cb[-1]<l[-2]-0.0010:
decision = SELL
tp = cb[-1]-0.010
sl = h[-2]+0.010
else:
decision = NONE
log_cols = ['time','volume','PAIR','bid_c','ask_c','mid_o','mid_h','mid_l','mid_c']
self.log_message(f"Processed_df\n{df[log_cols].tail(3)}")
self.log_message(f"Trade_decision:{decision}")
self.log_message("")
return decision
def get_trade_decision(self, candle_time):
max_rows = self.settings.long_ma + 2
self.log_message("")
self.log_message(f"get_trade_decision() pair:{self.pair} max_rows:{max_rows}")
df = self.fetch_candles(max_rows, candle_time)
print ("xxxx")
print (df)
if df is not None:
return self.process_candles(df)
print("get trade decision")
print(self.process_candles(df))
return NONE
bot.py
import pprint
import time
from settings import Settings
from log_wrapper import LogWrapper
from timing import Timing
from oanda_api import OandaAPI
from technicals import Technicals
from defs import NONE, BUY, SELL
from trade_manager import TradeManager
GRANULARITY = "M1"
SLEEP = 10.0
class TradingBot():
def __init__(self):
self.log = LogWrapper("Bot")
self.tech_log = LogWrapper("Technicals")
self.trade_log = LogWrapper("Trade")
self.trade_pairs = Settings.get_pairs()
self.settings = Settings.load_settings()
self.api = OandaAPI()
self.trade_manager = TradeManager(self.api, self.settings, self.trade_log)
self.timings = { p: Timing(self.api.last_complete_candle(p, GRANULARITY)) for p in self.trade_pairs }
self.log_message(f"Bot started with\n{pprint.pformat(self.settings)}")
self.log_message(f"Bot Timings\n{pprint.pformat(self.timings)}")
print (self.api)
def log_message(self, msg):
self.log.logger.debug(msg)
def update_timings(self):
for pair in self.trade_pairs:
current = self.api.last_complete_candle(pair, GRANULARITY)
self.timings[pair].ready = False
if current > self.timings[pair].last_candle:
self.timings[pair].ready = True
self.timings[pair].last_candle = current
self.log_message(f"{pair} new candle {current}")
def process_pairs(self):
trades_to_make = []
for pair in self.trade_pairs:
if self.timings[pair].ready == True:
self.log_message(f"Ready to trade {pair}")
techs = Technicals(self.settings[pair], self.api, pair, GRANULARITY, log=self.tech_log)
decision = techs.get_trade_decision(self.timings[pair].last_candle)
print ("process decision")
print (decision)
units = decision * self.settings[pair].units
#tp = "154"
#sl = "153"
if units != 0:
trades_to_make.append({'pair': pair, 'units': units,'take_profit':tp, 'stop_loss':sl})
if len(trades_to_make) > 0:
print("bot")
print(trades_to_make)
self.trade_manager.place_trades(trades_to_make)
def run(self):
while True:
self.update_timings()
self.process_pairs()
time.sleep(SLEEP)
if __name__ == "__main__":
b = TradingBot()
b.run()
defs.py
API_KEY = "xxxx"
ACCOUNT_ID = "xyz"
OANDA_URL = 'https://api-fxpractice.oanda.com/v3'
SECURE_HEADER = {
'Authorization': f'Bearer {API_KEY}',
'Content-Type': 'application/json'
}
BUY = 1
SELL = -1
NONE = 0
Instead of just returning the decision, also return the take profit and stop loss values:
return decision, tp, sl
Then you can unpack the tuple in process_pairs:
decision, tp, sl = techs.get_trade_decision(self.timings[pair].last_candle)
You can define your tp and sl as class variables of Technicals.
class Technicals(object):
tp: int = 0
sl: int = 0
and use them within Technicals as:
cls.tp = ... # if you are inside class-method
self.tp = ... # if you are inside instance-method
And in the TradingBot you can then simple import Technicals and use the class-Vars like:
tp = Technicals.tp # you can use the class
tp = techs.tp # or the instance you already have
I have a script in Maya (python) that renders a series of frames to the V-ray frame buffer, one for each render layer. It is working well, but when switching render layers and launching the next render, Maya grabs focus, interrupting whatever task the artist had moved on to while the script was running. I would like this to be a background task. Maya is running on Windows.
import maya
import maya.cmds as cmds
import re
from functools import partial
import sys
from datetime import datetime
global cancel
cancel = 0
print 'batch_review'
def no_cam_window_popup(no_cam_set_list):
#print no_cam_set_list
cmds.window(title = 'WARNING: NO CAMERAS LINKED TO LAYERS', width = 300, height = 75, sizeable = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = ("no cam set for layers:"))
for layer in no_cam_set_list:
cmds.text(label = ('' + layer + ', '),font = 'boldLabelFont')
cmds.showWindow()
def renderThumbs(checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld,*args):
global cancel
cams = cmds.ls(type = "camera")
cancel = 0
popup_win = 0
no_cam_set_list = []
cmds.loadPlugin('vrayformaya', quiet=True)
cmds.pluginInfo('vrayformaya', edit=True, autoload=True)
cmds.setAttr("defaultRenderGlobals.ren", "vray", type = "string")
curLay = cmds.editRenderLayerGlobals( currentRenderLayer = True, query = True )
changeLay = curLay
rls = cmds.ls(type = "renderLayer")
renCams = cmds.ls(type = "camera")
renCam = "persp"
lowBut = cmds.checkBox(checkBoxLow,value = True, query = True)
midBut = cmds.checkBox(checkBoxMid,value = True, query = True)
highBut = cmds.checkBox(checkBoxHigh,value = True, query = True)
globopt_cache_geom_plugins = cmds.getAttr('vraySettings.globopt_cache_geom_plugins')
#print 'globopt_cache_geom_plugins = ',globopt_cache_geom_plugins
print " "
print "-- batch_review --"
res = cmds.intField(intField_res, v = True, query = True)
thr = cmds.floatField(floatField_thrhld, v = True,query = True)
if lowBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if midBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
if highBut == 1:
cmds.setAttr("vraySettings.dmcThreshold",thr)
cmds.setAttr("vraySettings.width", res)
cmds.setAttr("vraySettings.height", res)
cmds.setAttr("vraySettings.globopt_cache_geom_plugins",1)
cmds.setAttr("vraySettings.globopt_ray_maxIntens_on",1)
#cmds.setAttr('vraySettings.globopt_cache_geom_plugins',globopt_cache_geom_plugins)
print " "
print "---"
print "quality = %s, dmcThreshold = %s"%(res,thr)
print "--- "
print " "
for rl in rls:
found_cam = 0
if rl != "defaultRenderLayer" and cancel == 0:
rlState = cmds.getAttr(rl + ".renderable")
if rlState == 1:
print ' '
print "rende layer = ",rl
cmds.editRenderLayerGlobals( currentRenderLayer = rl )
for cam in cams:
camState = cmds.getAttr(cam + ".renderable")
if camState == 1:
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
print 'using ' + cam + ' for ' + rl
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
print " "
found_cam = 1
if found_cam == 0:
print 'no camera link found, using persp cam for ',rl
cam = 'persp'
rrState = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
reg = cmds.vray("vfbControl","-getregion")
if rrState == 0:
cmds.vray("vfbControl","-setregion","reset")
if rrState == 1:
cmds.vray("vfbControl","-setregionenabled",1)
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
mayaString = "renderWindowRenderCamera render renderView " + cam
maya.mel.eval(mayaString)
cmds.vray("vfbControl", "-historysave")
cmds.vray("vfbControl", "-historyselect",0)
dte = datetime.now().strftime('%H:%M:%S')
editStr = dte + " ,render layer: " + rl + " , " + "cam: " + cam
cmds.vray("vfbControl", "-historycomment", editStr)
popup_win = 1
no_cam_set_list.append(rl)
#if popup_win == 1:
#no_cam_window_popup(no_cam_set_list)
def checkBoxCheckLow(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 800,edit = True)
cmds.floatField(floatField_thrhld, v = .1,edit = True )
cancel = 0
def checkBoxCheckMid(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxHigh,value = False, edit = True)
cmds.intField(intField_res, v = 1000,edit = True)
cmds.floatField(floatField_thrhld, v = .5,edit = True )
cancel = 0
def checkBoxCheckHigh(checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld,*args):
global cancel
lowButVal = cmds.checkBox(checkBoxLow,value = True, query = True)
midButVal = cmds.checkBox(checkBoxMid,value = True, query = True)
highButVal = cmds.checkBox(checkBoxHigh,value = True, query = True)
cmds.checkBox(checkBoxLow,value = False, edit = True)
cmds.checkBox(checkBoxMid,value = False, edit = True)
cmds.intField(intField_res, v = 2000,edit = True)
cmds.floatField(floatField_thrhld, v = .008,edit = True )
cancel = 0
def checkBoxAOVchange(checkBoxAOV,*args):
checkBoxAOVval = cmds.checkBox(checkBoxAOV,value = True,query = True)
if checkBoxAOVval == 1:
cmds.setAttr("vraySettings.relements_enableall", 1)
if checkBoxAOVval == 0:
cmds.setAttr("vraySettings.relements_enableall", 0)
def rrCheckbox(checkBoxRenderRegion,reg,*args):
global gReg
zeroes = ['0','0','0','0']
tRes = cmds.vray("vfbControl","-getregion")
if tRes != zeroes:
gReg = tRes
rrstate = cmds.checkBox(checkBoxRenderRegion,value = True,query = True)
if rrstate == 0:
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
cmds.vray("vfbControl","-setregion","reset")
if rrstate == 1:
cmds.vray("vfbControl","-setregionenabled",1)
if gReg != zeroes:
cmds.vray("vfbControl","-setregion",gReg[0],gReg[1],gReg[2],gReg[3])
else:
cmds.vray("vfbControl","-setregion",reg[0],reg[1],reg[2],reg[3])
return(reg)
def cancelOPs(*args):
global cancel
cancel = 1
raise Exception("quitting renders")
def set_threshhold(floatField_thrhld,*args):
threshhold_value = cmds.floatField(floatField_thrhld,value = True,query = True)
cmds.setAttr('vraySettings.dmcThreshold',threshhold_value)
def set_resolution(intField_res,*args):
intField_res_value = cmds.intField(intField_res,value = True,query = True)
cmds.setAttr('vraySettings.width',intField_res_value)
cmds.setAttr('vraySettings.height',intField_res_value)
def renthumbsWin():
name = "Batch_Review"
global gReg
gReg = ('0','0','0','0')
zeroes = ('0','0','0','0')
windowSize = (200,100)
if (cmds.window(name, exists = True)):
cmds.deleteUI(name)
window = cmds.window(name, title = name, width = 350, height = 50,bgc = (.2,.2,.2), s = False)
cmds.columnLayout("mainColumn", adjustableColumn = True)
cmds.rowLayout("nameRowLayout01", numberOfColumns = 15, parent = "mainColumn")
cmds.text(label = "preset quality: ")
checkBoxLow = cmds.checkBox(label = "low", value = False)
checkBoxMid = cmds.checkBox(label = "mid", value = True,)
checkBoxHigh = cmds.checkBox(label = "high", value = False)
cmds.text(label = " ")
cmds.text(label = "resolution: ")
intField_res = cmds.intField(v = 1000,width = 45)
#print 'intField_res = ',intField_res
cmds.intField(intField_res, changeCommand = partial(set_resolution,intField_res),edit = True)
cmds.text(label = " ")
cmds.text(label = "threshold: ")
floatField_thrhld = cmds.floatField(v = .5,width = 45)
cmds.floatField(floatField_thrhld, changeCommand = partial(set_threshhold,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxLow, changeCommand = partial(checkBoxCheckLow,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld), edit = True)
cmds.checkBox(checkBoxMid, changeCommand = partial(checkBoxCheckMid,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.checkBox(checkBoxHigh, changeCommand = partial(checkBoxCheckHigh,checkBoxLow,checkBoxMid,checkBoxHigh,intField_res,floatField_thrhld),edit = True)
cmds.rowLayout("nameRowLayout02", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout03", numberOfColumns = 5, parent = "mainColumn")
renderButton = cmds.button(label = "render",width = 100, bgc = (.6,.8,1) )
cmds.text(label = " ")
cmds.button(label = "cancel renders", command = partial(cancelOPs),bgc = (1,.3,.3) )
cmds.rowLayout("nameRowLayout04", numberOfColumns = 10, parent = "mainColumn")
cmds.text(label = " ")
cmds.rowLayout("nameRowLayout05", numberOfColumns = 10, parent = "mainColumn")
checkBoxRenderRegion = cmds.checkBox(label = "use render region", value = False)
cmds.text(label = " ")
cmds.text(label = " ")
reg = cmds.vray("vfbControl","-getregion")
if reg != gReg and reg != zeroes:
gReg = reg
cmds.vray("vfbControl","-setregion","reset")
cmds.checkBox(checkBoxRenderRegion,changeCommand = partial(rrCheckbox,checkBoxRenderRegion,reg),edit = True)
cmds.rowLayout("nameRowLayout06", numberOfColumns = 10, parent = "mainColumn")
AOVstate = cmds.getAttr("vraySettings.relements_enableall")
checkBoxAOV = cmds.checkBox(label = "elements", value = AOVstate)
cmds.checkBox(checkBoxAOV,changeCommand = partial(checkBoxAOVchange,checkBoxAOV),edit = True)
cmds.button(renderButton,command = partial(renderThumbs,checkBoxLow,checkBoxMid,checkBoxHigh,checkBoxRenderRegion,intField_res,floatField_thrhld),edit = True)
cmds.showWindow()
def main():
renthumbsWin()
main()
I'm trying to select multiple curve cvs
these are my function's codes
this is setArg Func:
import maya.cmds as mc from functools import partial
def setArg(CTS, option, *args):
option = mc.radioButtonGrp(CTS, q=True, select=True)
if option == 1:
cvToSel = 'first'
print cvToSel
elif option == 2:
cvToSel = 'last'
print cvToSel
return cvToSel
this is execute Func:
def execute(cvToSel, *args):
newSel = []
curves = mc.listRelatives (type = 'nurbsCurve', shapes = True)
if not curves:
print ('no curves selected')
#mc.select(clear = True)
#print curves
for crv in curves:
len = mc.getAttr(crv+'.cp', s=True, multiIndices=True)
cvSelect = mc.intFieldGrp('numberOfCvs', q = True, value1 = True)
numCv = len - cvSelect
if cvToSel == 'last':
newSel = mc.select(crv+'.cv[%d'%numCv +':%d]'%len, tgl = True)
elif cvToSel == 'first':
newSel = mc.select(crv+'.cv[0' + ':%d]'%cvSelect, tgl = True)
#mc.select(newSel, replace = True)
this is ui Func:
def ui():
if mc.window('CV_Select', exists = True):
mc.deleteUI('CV_Select')
cvWin = mc.window('CV_Select', mxb = False)
mc.columnLayout( adjustableColumn = True )
mc.text( label = 'select curves' )
mc.intFieldGrp( 'numberOfCvs', label = 'Number Of Cvs', value1 = 10 )
ButtonOne = mc.radioButtonGrp( label='Type', labelArray2=['First CVs', 'Last CVs'], numberOfRadioButtons = 2)
mc.button( label = 'Select CVs', command = partial(execute, ButtonOne), align = 'center', aop = True)
mc.showWindow('CV_Select')
ui()
How do I use arguments?
first dont use 'len' to store a variable. it is a python function really useful....
Here is a way to do it. You need to put your select function outside your loop
You could use -add flag but it can be really slow
Store first cvs into a variable :
(i dont have maya until Monday but I hope it will help)
sel_curves = mc.ls(sl=1, dag=1, type='nurbsCurve')
if sel_curves:
to_sel = []
cvSelect = mc.intFieldGrp('numberOfCvs', q = True, value1 = True)
for c in sel_curves:
cvs = mc.ls(c+'.cv[:]', fl=True)
nb_cvs = len(cvs)
if cvSelect > nb_cvs:
nb_cvs = cvSelect
if cvToSel == 'last':
to_sel += cvs[cvSelect:]
elif cvToSel == 'first':
to_sel += cvs[:cvSelect]
cmds.select(to_sel, tgl = True)
--- EDIT ---
Just to answer your comment question :
def execute(CTS,*args):
cvToSel = setArg(CTS)