How to add an integer to a string in python - Oanda API - python

I am trying add a stop loss order along with a buy order using Oanda's REST API. As of right now I can easily specify a price for a stop loss, however, I would like to calculate my stop based on the current price. For instance "current_price" + .1 . I am not very familiar with Python, hence the simple question, but this is driving me nuts. Any help would be appreciated!
I get this error code (along with many others when I try and fix the problem)
trading.py", line 41, in <module>
stopLoss = float("bid") -- float(.01)
ValueError: could not convert string to float: bid
Thanks in advance, code as follows
trading.py
import Queue
import threading
import time
from execution import Execution
from settings import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy import TestRandomStrategy
from streaming import StreamingForexPrices
def trade(events, strategy, execution):
"""
Carries out an infinite while loop that polls the
events queue and directs each event to either the
strategy component of the execution handler. The
loop will then pause for "heartbeat" seconds and
continue.
"""
while True:
try:
event = events.get(False)
except Queue.Empty:
pass
else:
if event is not None:
if event.type == 'TICK':
strategy.calculate_signals(event)
elif event.type == 'ORDER':
print "Executing order!"
execution.execute_order(event)
time.sleep(heartbeat)
if __name__ == "__main__":
heartbeat = 0 # Half a second between polling
events = Queue.Queue()
# Trade 1000 unit of EUR/USD
instrument = "EUR_USD"
units = 1000
stopLoss = float("bid") -- float(.01)
# Create the OANDA market price streaming class
# making sure to provide authentication commands
prices = StreamingForexPrices(
STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
instrument, events
)
# Create the execution handler making sure to
# provide authentication commands
execution = Execution(API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID)
# Create the strategy/signal generator, passing the
# instrument, quantity of units and the events queue
strategy = TestRandomStrategy(instrument, units, events, stopLoss)
# Create two separate threads: One for the trading loop
# and another for the market price streaming class
trade_thread = threading.Thread(target=trade, args=(events, strategy, execution))
price_thread = threading.Thread(target=prices.stream_to_queue, args=[])
# Start both threads
trade_thread.start()
price_thread.start()
execution.py
import httplib
import urllib
class Execution(object):
def __init__(self, domain, access_token, account_id):
self.domain = domain
self.access_token = access_token
self.account_id = account_id
self.conn = self.obtain_connection()
def obtain_connection(self):
return httplib.HTTPSConnection(self.domain)
def execute_order(self, event):
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + self.access_token
}
params = urllib.urlencode({
"instrument" : event.instrument,
"units" : event.units,
"type" : event.order_type,
"side" : event.side,
"stopLoss" : event.stopLoss
})
self.conn.request(
"POST",
"/v1/accounts/%s/orders" % str(self.account_id),
params, headers
)
response = self.conn.getresponse().read()
print response
Event.py
class Event(object):
pass
class TickEvent(Event):
def __init__(self, instrument, time, bid, ask):
self.type = 'TICK'
self.instrument = instrument
self.time = time
self.bid = bid
self.ask = ask
class OrderEvent(Event):
def __init__(self, instrument, units, order_type, side, stopLoss):
self.type = 'ORDER'
self.instrument = instrument
self.units = units
self.order_type = order_type
self.side = side
self.stopLoss = stopLoss
Strategy.py
import random
from event import OrderEvent
class TestRandomStrategy(object):
def __init__(self, instrument, units, events, stopLoss):
self.instrument = instrument
self.units = units
self.events = events
self.ticks = 0
self.stopLoss = stopLoss
def calculate_signals(self, event):
if event.type == 'TICK':
self.ticks += 1
if self.ticks % 1 == 0:
side = random.choice(["buy"])
order = OrderEvent(
self.instrument, self.units, "market", side, self.stopLoss
)
self.events.put(order)
Thanks again..

If you want to combine string and you should convert float to string
""+str(.1)

Related

How to use other def values?

I want to use other def values.
For example, I added a 'pt' in the 'clean_beds_process' definition and add 'Patients' in the 'run' definition.
I want to patient information when the 'clean_beds_process' function is called.
However, this makes this error 'AttributeError: type object 'Patients' has no attribute 'id''
I don't know why this happen.
Maybe I have something wrong understanding of mechanism of simpy.
Please let me know how can I use a patient information when 'clean_beds_process' function is called.
Thank you.
import simpy
import random
class Patients:
def __init__(self, p_id):
self.id = p_id
self.bed_name = ""
self.admission_decision = ""
def admin_decision(self):
admin_decision_prob = random.uniform(0, 1)
if admin_decision_prob <= 0.7:
self.admission_decision = "DIS"
else:
self.dmission_decision = "IU"
return self.admission_decision
class Model:
def __init__(self, run_number):
self.env = simpy.Environment()
self.pt_ed_q = simpy.Store(self.env )
self.pt_counter = 0
self.tg = simpy.Resource(self.env, capacity = 4)
self.physician = simpy.Resource(self.env, capacity = 4)
self.bed_clean = simpy.Store(self.env)
self.bed_dirty = simpy.Store(self.env)
self.IU_bed = simpy.Resource(self.env, capacity = 50)
def generate_beds(self):
for i in range(77):
yield self.env.timeout(0)
yield self.bed_clean.put(f'bed{i}')
def generate_pt_arrivals(self):
while True:
self.pt_counter += 1
pt = Patients(self.pt_counter)
yield self.env.timeout(5)
self.env.process(self.process(pt))
def clean_beds_process(self, cleaner_id, pt):
while True:
print(pt.id)
bed = yield self.bed_dirty.get()
yield self.env.timeout(50)
yield self.bed_clean.put(bed)
def process(self, pt):
with self.tg.request() as req:
yield req
yield self.env.timeout(10)
bed = yield self.bed_clean.get()
pt.bed_name = bed
pt.admin_decision()
if pt.admission_decision == "DIS":
with self.IU_bed.request() as req:
dirty_bed_name = pt.bed_name
yield self.bed_dirty.put(dirty_bed_name)
yield self.env.timeout(600)
else:
dirty_bed_name = pt.bed_name
yield self.bed_dirty.put(dirty_bed_name)
def run(self):
self.env.process(self.generate_pt_arrivals())
self.env.process(self.generate_beds())
for i in range(2):
self.env.process(self.clean_beds_process(i+1, Patients))
self.env.run(until = 650)
run_model = Model(0)
run_model.run()
So if a patient can use either a clean bed or a dirty bed then the patient needs to make two request (one for each type of bed) and use env.any_of to wait for the first request to fire. You also need to deal with the case that both events fire at the same time. Don't forget to cancel the request you do not use. If the request that fires is for a clean bed, things stay mostly the same. But if the request is for a dirty bed, then you need to add a step to clean the bed. For this I would make the cleaners Resources instead of processes. So the patient would request a cleaner, and do a timeout for the cleaning time, release the cleaner. To collect patient data I would create a log with the patient id, key event, time, and crunch these post sim to get the stats I need. To process the log I often create a dataframe that filters the log for the first, a second dataframe that filters for the second envent, join the two dataframes on patient id. Now both events for a patient is on one row so I can get the delta. once I have have the delta I can do a sum and count. For example, if my two events are when a patient arrives, and when a patient gets a bed, get the sum of deltas and divide by the count and I have the average time to bed.
If you remember, one of the first answers I gave you awhile ago had a example to get the first available bed from two different queues
I do not have a lot of time right know, but I hope this dissertation helps a bit

Class objects and Multi threading in python

I am using multithreading for the first time and here is the problem in which I am stuck.
I have a class Workstation and want to use a separate thread for each instance of the class. Each instance has to draw some cell phone models defined in the global list, but multithreading does not work for all instances, it works well only for one object and the rest seem to hang.
Here is code for my class and in the main file I am using another thread(code for that also attached below the class code) that runs a while loop forever and inside that loop, I am calling "drawing_thread"
function for each object of workstation-class.
why threading only works for the first object, not for others
import requests, time, db_quries, threading
from datetime import datetime
import helper_functions as HF
LocIP = '192.168.100.100'
# Local port for server
LocPort = 4321
class Workstation:
def __init__(self,FCell):
"""
constructor for class workstation
:param FCell:
"""
self.FCell = FCell # cell number
#initial values of component's flag
self.frame_done = True
self.screen_done = False
self.kpad_done = False
#flags for order compeltion
self.make = 1
self.complete = 0
self.thread_flag=True
#mutators for object variables
def make_setter(self):
self.make = self.make+1
#print('FL1: Make ',self.make)
def set_m(self,m):
self.make=m
def complete_setter(self,complete):
self.complete =complete
#print('FL1: complete ',self.complete)
def set_frame(self, value):
self.frame_done = value
def set_screen(self, value):
self.screen_done = value
def set_kpad(self, value):
self.kpad_done = value
def set_thread_flag(self,value):
self.thread_flag = value
def drawing_thread(self,param):
self.thread_flag = False
drawing = threading.Thread(target=HF.production, args=param)
drawing.start()
function that called by thread in main file
def process_thread():
while True:
#print(len(OrderList))
if WS_obj_list[0].thread_flag and WS_obj_list[0].get_zone_status('Z1') != '-1':
WS_obj_list[0].drawing_thread((WS_obj_list[0], OrderList))
if WS_obj_list[1].thread_flag and WS_obj_list[1].get_zone_status('Z1') != '-1':#
WS_obj_list[1].drawing_thread((WS_obj_list[1], OrderList))
if WS_obj_list[2].thread_flag and WS_obj_list[2].get_zone_status('Z1') != '-1':
WS_obj_list[2].drawing_thread((WS_obj_list[2], OrderList))
time.sleep(1)

How to pass the value of a variable of a class to another class?

I have an infinite loop that updates the currentPrice variable in the streamingPrice class, I need to use the value of this variable Trading class, the refresh function in Trading class is going to keep retrieving the value of the currentPrice every time it updates, then I'm going to perform a task on it. The stream and refresh functions have their own threads. How can I achieve that?
Currently I only get the initialized value of that variable
class streamingPrice():
def __init__(self):
self.currentPrice =0
def stream(self):
#Streaming live prices
api = API(access_token=userVals.key)
params = { "instruments": userVals.pair }
r = pricing.PricingStream(accountID=userVals.accountID, params=params)
rv = api.request(r)
for ticks in rv:
if('asks' in ticks):
self.setPrice(ticks['asks'][0]['price'])
def setPrice(self,price):
self.currentPrice = price
def getPrice(self):
return self.currentPrice
class Trading():
def refresh(self):
while(True):
#initialize data channel
self.highList, self.LowList, self.closeList = self.c.getData()
self.tradeCurrentPrice = self.sp.getPrice()
#Initialize Indicators
self.rolling_bands_low = self.s.ROLLING_BANDS_LOW(self.closeList)
self.rolling_bands_high = self.s.ROLLING_BANDS_HIGH(self.closeList)
self.stochostic_oscillator_k =
self.s.STOCHASTIC_OSCILLATOR_K(self.highList, self.LowList,
self.closeList)
self.stochostic_oscillator_d =
self.s.STOCHASTIC_OSCILLATOR_D(self.highList, self.LowList,
self.closeList)
self.tradeCurrentPrice = self.sp.getPrice() is wrong because you have not defined self.sp.
Based on your title I assume you want to do something like this:
sp = StreamingPrice()
trade = Trading(sp.currentPrice)
passing in the current price attribtue of the sp object into the new object.
Your Trading class will also need an __init__(self, price) method
there's also no need to create these methods:
def setPrice(self,price):
self.currentPrice = price
def getPrice(self):
return self.currentPrice
because you can achieve the same result doing this:
price = 3
sp = StreamingPrice()
sp.currentPrice = price

Dynamic class in python

It is probably the wrong title, but here is my problem.
I have a system comprised of a microcontroller (MCU), a serial interface (SPI), a DAC (Digital / Analog converter), an electrode (E). Each element is defined as a class in my python modelization.
As a first step, I want to monitor the output on the electrode as I input something in the microcontroller.
Let's consider the following:
Input: 2 mA on the electrode during 1 ms.
MCU send the new DAC value via the SPI: 30 us
DAC updates its register and output: 400 us
MCU send a switch on command to the electrode: 1 us
The electrode is now outputting.
1 ms later, send a switch off command to the electrode: 1us
The electrode doesn't output anymore.
My 2 biggest issues are 1. How to take into account this time component and 2. How to monitor the SPI line to determine if something has to be done.
class Electrode:
def __init__(self, id):
self.id = id
self.switch = False
self.value = 0
def output(self):
if self.switch:
return self.value
else:
return 0
class SPI:
def __init__(self):
self.msg = None
class MCU:
def __init__(self):
self.name = "MicroController"
def send_SPI_msg(self, SPI, msg):
SPI.msg = msg
class DAC:
def __init__(id):
self.id = id
self.cs = 1
self.register = None
self.output = None
def read_SPI_msg(self, SPI):
message = SPI.msg
# update register and output
My system actually has 16 DACs and electrodes and a field-programmable gate array which are all listening to the same SPI. What I described above is a fairly simplified version.
Question is: How to have the components check the value in SPI.msg regularly and act accordingly?
In reality, each component is doing its life. Thus actions are performed in parallel. Since I'm trying to simulate the timeline and the action performed, I do not mind doing everything serially with a timeline variable (attribute) for each element. I just have issues to figure out how to have my classes interact together.
i.e. I can't do the following in python or I will get stuck:
class DAC:
def __init__(id):
# init
def read_SPI_msg(self, SPI):
while True:
message = SPI.msg
# update register and output if needed
Maybe an event triggering could be used... But I don't know how.
Maybe with multithreading, defining one thread / element?
EDIT: Current state:
class SPI:
def __init__(self):
self.attached_dacs = []
self.attached_fpga = []
self.attached_mcu = []
def attach_device(self, device):
if type(device) == DAC:
self.attached_dacs.append(device)
elif type(device) == FPGA:
self.attached_fpga.append(device)
elif type(device) == MCU:
self.attached_mcu.append(device)
def send_message(self, msg):
for device in self.attached_dacs + self.attached_fpga:
device.on_spi_message(self, msg)
class SpiAttachableDevice:
def on_spi_message(self, SPI, message):
if self.cs:
self.execute_SPI_message(message)
else:
return None
class DAC(SpiAttachableDevice):
def __init__(self, id):
self.id = id
self.cs = False # Not listening
def execute_SPI_message(message):
# Do stuff
class FPGA(SpiAttachableDevice):
def __init__(self):
self.electrodes = list()
self.cs = False # Not listening
def execute_SPI_message(message):
# Do stuff
class MCU:
def __init__(self):
self.electrodes = list()
I'm assuming you want to keep it single-threaded and you don't use asyncio. In this case, you might want to employ observer or pub/sub pattern when implementing the SPI:
class SPI:
def __init__(self):
self.attached_devices = []
def attach_device(self, device):
self.attached_devices.append(device)
def send_message(self, msg):
for device in self.attached_devices:
device.on_spi_message(self, msg)
class SpiAttachableDevice:
def on_spi_message(self, spi_instance, message):
raise NotImplementedError('subclass me!')
So you can use it like this:
spi = SPI()
device_1 = Device()
device_2 = Device()
spi.attach_device(device_1)
spi.attach_device(device_2)
spi.send_message('hello')
I haven't done anything to be able to send SPI messages from Device objects, but you can update the abstraction accordingly.
You could move the while loop simply outside:
class SPI:
def __init__(self, msg):
self.msg = msg
class Component:
def __init__(self, spi):
self.spi = spi
def tick(self, t):
msg = self.spi.msg
if msg = "...":
...
spi = SPI()
components = [Component(spi), ...]
for t in range(TOTAL_TIME):
for component in components:
component.tick(t)
As stated in your comment you want more a timeline view on what is happening. You can have an explicit timeline with which your components interact. External input (state changes) can be set beforehand in the same manner. To order the timemline I'll just run sort each time but it would probably be more performant to use something like a priority queue.
This mainly differs from Vovanrock2002 answer by not recursing in each timestep and having an explicit timeline.
class Component:
def __init__(self, timeline):
self._timeline = timeline
self._out = [] #all connected components
def poke(self, changed_object, time):
return []
class Clock(Component):
def __init__(self, timeline):
Component.__init__(self, timeline)
self._out.append(self)
self.msg = "tick"
self._timeline.append((200, self, msg))
def poke(self, time, changed_object, msg):
self._timeline.append((time + 200, self, self.msg))
timeline = []
spi = SPI(timeline)
components = [spi, Clock(timeline), ComponentA(timeline), ...]
timeline.append((500, spi, "new DAC value"))
while timeline:
timeline.sort(key=lambda event: event[0], reverse=True)
event = timeline.pop()
time, changed_component, msg:
for connected_component in changed_component._out:
connected_component.poke(time, changed_component, msg)
This way you have an explicit timeline (which you could also "record", just add each popped event to some list) and you can have arbitrarily connected components (e.g. if you want to have multiple SPIs).

Using NumPy for discrete networking request event simulator?

I need to simulate the requests and responses being processed by a network of routers and began small by creating a server class:
class NBServer:
"""Name based content server"""
def __init__(self, _id):
self.id = _id
self.requests = deque('x')
self.responses = deque('x')
self.req_load = 0
self.res_load = 0
self.color = ''
self.forwarding_table = {}
self.content_store = {}
self.pending_table = {}
def __str__(self):
return 'current load: ' + str(req_load + req_load)
def request(self, content_name, requester_id):
self.requests.append((content_name, requester_ids))
self.req_load += 1
def response(self, content_name, content_url):
self.responses.append((content_url, destination_ids))
return ((content_url, destination_ids))
def process(self):
for req in self.requests:
# Case 1: content in cache
if content_name in self.content_store:
return self.content_name[content_name]
# Case 2: duplicate request exists
elif content_name in self.pending_table:
self.pending_table[content_name].append(requester_id)
# Case 3: add to PT, forward to next router
else:
self.pending_table[content_name] = [requester_id]
response = response.popleft()
if response:
for dest_id in self.pending_table[content_name]:
nodes[dest_id].response(content_name, content_url)
del self.pending_table[content_name]
However, now I am getting confused on how the communication between the routers can be represented:
Any advice on how to do this with NumPy?
Any help is greatly appreciated!

Categories

Resources