如何在python中的字符串中添加整数-Oanda API [英] How to add an integer to a string in python - Oanda API
问题描述
我正在尝试使用Oanda的REST API将止损订单与购买订单一起添加.到目前为止,我可以轻松指定止损的价格,但是,我想根据当前价格计算止损.例如"current_price" + .1.我对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
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
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
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)
再次感谢..
推荐答案
如果要合并字符串,则应将float转换为字符串
If you want to combine string and you should convert float to string
""+str(.1)
这篇关于如何在python中的字符串中添加整数-Oanda API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!