问题描述
我正在尝试使用 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
先谢谢了,代码如下
交易.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()
执行.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
事件.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
策略.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)
再次感谢..
推荐答案
如果你想组合字符串,你应该将浮点数转换为字符串
If you want to combine string and you should convert float to string
""+str(.1)
这篇关于如何在python中向字符串添加整数 - Oanda API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!