mercredi 22 avril 2015

Received request with malformed body.. Python and REST API

I am getting this error when trying to pass a rate to a stopLoss order through Oanda's API:

code" : 41,
    "message" : "Received request with malformed body: 'units=1&instrument=
    EUR_USD&type=market&side=buy&stopLoss=%3Cmodule+%27streamer%27+from+%27%2FUsers%2Fmattduhon%2Fstreamer.py%27%3E'",

My problems seems to stem from the way that the streaming price gets passed to the order because if I poll the API and get a static price it works just fine.

So my question is, how can I format the output of the stream so that it is simply and integer because it looks to me like the API is seeing it as

%3Cmodule+%27streamer%27+from+%27%2FUsers%2Fmattduhon%2Fstreamer.py%27%3E'",

wich I do not at all understand..

Thanks in advance for all your help! Code as follows:

Streaming rates: Gets Streaming rate and drills it down to output only the ask price - .001

import requests
import json

from optparse import OptionParser

def connect_to_stream():
    """
    Environment           <Domain>
    fxTrade               stream-fxtrade.oanda.com
    fxTrade Practice      stream-fxpractice.oanda.com
    sandbox               stream-sandbox.oanda.com
    """

    # Replace the following variables with your personal ones
    domain = 'stream-fxpractice.oanda.com'
    access_token = 'xxxxxxxxxxxx'
    account_id = 'xxxxxxxxx'
    instruments = "EUR_USD"

    try:
        s = requests.Session()
        url = "https://" + domain + "/v1/prices?instruments=EUR_USD"
        headers = {'Authorization' : 'Bearer ' + access_token,
                   # 'X-Accept-Datetime-Format' : 'unix'
                  }
        params = {'instruments' : instruments, 'accountId' : account_id}
        req = requests.Request('GET', url, headers = headers, params = params)
        pre = req.prepare()
        resp = s.send(pre, stream = True, verify = False)
        return resp
    except Exception as e:
        s.close()
        print "Caught exception when connecting to stream\n" + str(e) 

def demo(displayHeartbeat):
    response = connect_to_stream()
    if response.status_code != 200:
        print response.text
        return
    for line in response.iter_lines(1):
        if line:
            try:
                msg = json.loads(line)
            except Exception as e:
                print "Caught exception when converting message into json\n" + str(e)
                return

            if displayHeartbeat:
                print line
            else:
                if msg.has_key("instrument") or msg.has_key("tick"):
                    print msg["tick"]["ask"] - .001
                    instrument = msg["tick"]["instrument"]
                    time = msg["tick"]["time"]
                    bid = msg["tick"]["bid"]
                    ask = msg["tick"]["ask"]

Trading program: This executes the trade orders and gives me the "Malformed Body" error or runs perfectly with a static stopLoss price..

import Queue
import threading
import time
import json
import oandapy
import streamer

from execution import Execution
from settings import STREAM_DOMAIN, API_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID
from strategy import TestRandomStrategy
from streaming import StreamingForexPrices
from event import TickEvent
from event import StopEvent

rates = streamer

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 = 1
    stopLoss = rates



    # Create the OANDA market price streaming class
    # making sure to provide authentication commands
    prices = StreamingForexPrices(
        STREAM_DOMAIN, ACCESS_TOKEN, ACCOUNT_ID,
        instrument, events
    )
    #handle stopLoss price
    rates = streamer

    # 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=[])
    rate_thread = threading.Thread(target=rates, args=[])

    # Start both threads
    trade_thread.start()
    price_thread.start()
    rates_thread.start()

Aucun commentaire:

Enregistrer un commentaire