Jump to content
james

Interpreting api response when placing new orders

Recommended Posts

Hello!

I am attempting to place new orders via the /newtradeorder as described on http://docs.labs.gaincapital.com/#HTTP Services/Trade.htm%3FTocPath%3DCIAPI%20Reference|HTTP%20Services|Trades%20and%20Orders|_____16

In trying to interpret the response, I am confused by the nested Status and StatusReason codes. Which lookup tables do each of these reference, and what do they tell me?  I believe my order is in 'open'' status, is that accurate? What does the Status of 1 on the first line represent, and which lookup table does that reference? Is that a 'Pending' status?

Perhaps I'm just too close to it for too long, but what exactly does a status of 'open' in this context mean? I am working from a demo account, will behavior be different in this context than a normal, live interaction?

I really appreciate any help or guidance!

Here is the response I receive:

 

{
  +"Status": 1
  +"StatusReason": 1
  +"OrderId": 692995594
  +"Orders": array:1 [
    0 => {#690
      +"OrderId": 692995594
      +"StatusReason": 1
      +"Status": 3
      +"OrderTypeId": 1
      +"Price": 1504.14
      +"Quantity": 1.0
      +"TriggerPrice": 0.0
      +"CommissionCharge": 0.0
      +"IfDone": []
      +"GuaranteedPremium": 0.0
      +"OCO": null
      +"AssociatedOrders": {#692
        +"Stop": null
        +"Limit": null
      }
      +"Associated": false
    }
  ]
  +"Quote": null
  +"Actions": array:1 [
    0 => {#727
      +"ActionedOrderId": 0
      +"ActioningOrderId": 0
      +"Quantity": 1.0
      +"ProfitAndLoss": 0.0
      +"ProfitAndLossCurrency": null
      +"OrderActionTypeId": 1
    }
  ]
  +"ErrorMessage": null
}

 

Share this post


Link to post

Hi James,

The call you are using places trades in your account, rather than entry orders. Hopefully that is what you were looking to do?

In the API response, the first set is always the InstructionStatus and InstructionStatusReason codes, which you can find in the lookup table at: http://docs.labs.gaincapital.com/#APICodesList.htm%3FTocPath%3DGetting%20Started|Lookup%20Values|_____1

The second set in the nested response is then the OrderStatus and OrderStatusReason codes. I have annotated the screenshot accordingly to illustrate this. 

OrderStatus = 3 representing Open, means you now have an open position as your trade request was accepted successfully. Should you login to your account on any of our trading platforms, you will see an open position in the Open Positions panel. 

The lookup codes in the API responses tell you whether your requests were successful or whether a problem was encountered. If a problem is encountered then the appropriate reason code should help shed light on how to fix the issue.

Using the API with a Live account will have the same behaviour.

Kind Regards, PM

image.png

 

Share this post


Link to post

Thank you for this information. It does seem like I am on track and doing what I want to be doing.

Quote

Should you login to your account on any of our trading platforms

I don't know what this means. What is a trading platform? If I can access information for this demo account in some way other than via the api, that would be most useful. Is there a web interface somewhere I can use?

Share this post


Link to post

Hi James,

Trading platforms are front-end interfaces that clients can use to place trades/orders, monitor market prices. check open positions etc. An example is our web browser platform Web Trader (see screenshot below).

Depending upon which brand where you have your trading account, such as FOREX.com, then the website for the brand will contain the login link and information for all our trading platforms. Aside from the Web browser platform, we have mobile Apps for iOS / Android and a downloadable PC installed platform. 

Kind Regards, PM

image.png

Share this post


Link to post

I tried to login as you described when the account was first set up and wasn't able to. I've just retried and was able to get right in. I must have been making an error with a username and password during the earlier attempts.  Thank you for the information and prompting me to retry!

I also really appreciate you pointing out that I am creating a trade rather than an entry order. It seems like I need to switch to the newstoplimitorder endpoint.

Share this post


Link to post

Sorry to be such a pest... I have a follow up question.

I'm now posting to /newstoplimitorder as you hinted at.  I can see the orders showing up via the platform - verifying things on that side is a huge step forward!

I aspire to set 'stop' and 'limit' values, and do not see those correctly set when viewing via the platform.

What is the correct way to set these values via the /newstoplimitorder endpoint?

I am currently trying to do so using the ifDone parameter thusly:

Quote

 "Applicability" => "GFD"
  "AuditId" => "XXXXXXXX"
  "AutoRollover" => false
  "BidPrice" => "1513.02"
  "Currency" => "USD"
  "Direction" => "buy"
  "ExpiryDateTimeUTC" => null
  "ExpiryDateTimeUTCDate" => null
  "isTrade" => false
  "LastChangedDateTimeUTC" => null
  "LastChangedDateTimeUTCDate" => null
  "MarketId" => "401153870"
  "MarketName" => "XAU/USD"
  "OcoOrder" => null
  "OfferPrice" => "1513.53"
  "OrderId" => 0
  "PositionMethodId" => 1
  "Quantity" => 1
  "QuoteId" => null
  "Reference" => "GCAPI"
  "Status" => null
  "TradingAccountId" => XXXXX
  "TriggerPrice" => "1513.28"
  "Type" => null
  "IfDone" => array:2 [
    "stop" => array:2 [
      "Applicability" => "GFD"
      "TriggerPrice" => 1509.0
    ]
    "limit" => array:2 [
      "Applicability" => "GFD"
      "TriggerPrice" => 1517.0
    ]
  ]
]

 

Share this post


Link to post

Hi James,

1) I just want to clarify the following to check that I have understood what you are trying to do. You are placing an entry order together with "if/done" stop and limit orders, so that if the entry order is filled and becomes an open position (trade), then it will have a stop loss or take profit limit orders attached?

2) Are you a FOREX.com US client? If you are, then that explains why you are not able to place entry orders with attached stops/limit orders. US clients fall under the jurisdiction of the NFA regulator, and they have forbidden being able to place entry orders with attached if/done stop or limit orders. 

Kind Regards, PM 

Share this post


Link to post

Hi PM,

I think I'm getting confused on language here.

I am indeed a FOREX.com US client.

My end goal is to have an open trade with a stop and limit set. Is there a good way for me to achieve that?

EDIT:

I've switched back to using the /newtradeorder endpoint. Does the NFA regulation you cited apply to calls to this endpoint as well?

I'm referencing another forum post as an example, but the response I receive doesn't have if/then values set:

The data I am sending is:

 

Quote

 [
  "Applicability" => "GFD"
  "AuditId" => "GTXLON42949"
  "AutoRollover" => false
  "BidPrice" => "1523.98"
  "Currency" => "USD"
  "Direction" => "buy"
  "ExpiryDateTimeUTC" => null
  "ExpiryDateTimeUTCDate" => null
  "isTrade" => false
  "LastChangedDateTimeUTC" => null
  "LastChangedDateTimeUTCDate" => null
  "MarketId" => "401153870"
  "MarketName" => "XAU/USD"
  "OcoOrder" => null
  "OfferPrice" => "1524.44"
  "OrderId" => 0
  "PositionMethodId" => 1
  "Quantity" => 1
  "QuoteId" => null
  "Reference" => "GCAPI"
  "Status" => null
  "TradingAccountId" => XXXXXXX
  "TriggerPrice" => "1524.21"
  "Type" => null
  "IfDone" =>  [
    "Stop" =>  [
      "OrderId" => null
      "Direction" => "sell"
      "Applicability" => "gtc"
      "ExpiryDateTimeUTC" => null
      "Quantity" => 1
      "TriggerPrice" => 1522.8
      "IfDone" => []
      "OcoOrder" => null
    ]
    "Limit" =>  [
      "OrderId" => null
      "Direction" => "sell"
      "Applicability" => "gtc"
      "ExpiryDateTimeUTC" => null
      "Quantity" => 1
      "TriggerPrice" => 1525.6
      "IfDone" => []
      "OcoOrder" => null
    ]
  ]
]

 

 

Edited by james
provide more detail of model and data I am sending

Share this post


Link to post

Hi James,

Confusion in the language is indeed possible, which is why I wanted to clarify to ensure we are talking about the same thing.

Let's use a concrete example to make things more clear. Say we are looking at EUR/USD with current Sell / Buy market price of: 1.10818 / 1.10832, and we are looking to buy this market for 10,000.

Which of the following 2 cases are you trying to use?

Case 1: Buy 10,000 EUR/USD immediately at the current market price of 1.10832 and have attached stop loss / take profit limit orders to the open position.

Case 2: Wait for the market to pull back to a different price, say 1.10200. If the market does pull back and touch 1.10200, only then do you want the system to automatically buy 10,000 at 1.10200 with attached stop loss / take profit limit orders attached to that future open position.

 

================

 

It is Case 2 that is forbidden for US clients - Case 1 is allowed and possible using our API.

To perform Case 1, you would send a call to the /newtradeorder endpoint and the payload would look something similar to:

{"MarketId":xxxx,"Direction":"buy","Quantity":10000,"BidPrice":1.10818,"OfferPrice":1.10832,"TradingAccountId":xxxx,"PositionMethodId":1,
  "IfDone":[{"Stop":{"OrderId":null,"Direction":"sell","Applicability":"gtc","ExpiryDateTimeUTC":null,"Guaranteed":false,"Quantity":10000,"TriggerPrice":1.09835,"IfDone":[],"OcoOrder":null},
             "Limit":{"OrderId":null,"Direction":"sell","Applicability":"gtc","ExpiryDateTimeUTC":null,"Quantity":10000,"TriggerPrice":1.11835,"IfDone":[],"OcoOrder":null}}]}

 

Kind Regards, PM

 

Share this post


Link to post

I am after case 1. I want an immediate position at the current market price. So I will stick with /newtradeorder

I've compared the payload example you have provided with what I am sending. I did have a number of extra parameters which I understood to be required, and have removed those. 

I have run a number of tests. Bid Price and Offer Price are always set on the latest price obtained from a lightstreamer connection.  I am seeing mixed results.

Most often the response status code is:

Quote

Instruction: Red Card
Instruction Reason: Instruction processing has resulted in a Red Card. Please check details.
Status: Accepted
Status Reason: Instruction processing has resulted in a Red Card. Please check details.

Other times the response is okay, and the trade is accepted. However, in those cases, I am not seeing the stop or limit in the response or when I view the position via the trading platform.

I have two questions -

1) What might be causing the red card? I don't see any additional information in the response - what details is it referencing?

2) Am I understanding correctly that the null IfDone array in the response points towards those values having been rejected? If so, what might be causing that?

Here is the request I am sending:

{
  "BidPrice": "1511.21",
  "Direction": "buy",
  "MarketId": "401153870",
  "OfferPrice": "1511.66",
  "PositionMethodId": 1,
  "Quantity": 1,
  "TradingAccountId": "401589313",
  "IfDone": {
    "Stop": {
      "Applicability": "gtc",
      "Direction": "sell",
      "ExpiryDateTimeUTC": null,
      "Guaranteed": false,
      "IfDone": [],
      "OcoOrder": null,
      "OrderId": null,
      "Quantity": 1,
      "TriggerPrice": 1510.94
    },
    "Limit": {
      "Applicability": "gtc",
      "Direction": "sell",
      "ExpiryDateTimeUTC": null,
      "IfDone": [],
      "OcoOrder": null,
      "OrderId": null,
      "Quantity": 1,
      "TriggerPrice": 1511.94
    }
  }
}

 

and here is the response:

{
  "Status": 1,
  "StatusReason": 1,
  "OrderId": 693438627,
  "Orders": [
    {
      "OrderId": 693438627,
      "StatusReason": 1,
      "Status": 3,
      "OrderTypeId": 1,
      "Price": 1511.58,
      "Quantity": 1,
      "TriggerPrice": 0,
      "CommissionCharge": 0,
      "IfDone": [],
      "GuaranteedPremium": 0,
      "OCO": null,
      "AssociatedOrders": {
        "Stop": null,
        "Limit": null
      },
      "Associated": false
    }
  ],
  "Quote": null,
  "Actions": [
    {
      "ActionedOrderId": 0,
      "ActioningOrderId": 0,
      "Quantity": 1,
      "ProfitAndLoss": 0,
      "ProfitAndLossCurrency": null,
      "OrderActionTypeId": 1
    }
  ],
  "ErrorMessage": null
}

Thanks so much for all your help and advice!

- James

Share this post


Link to post

hello @Physicsman Very clear response thank you, by the way do you have any Idea of how to get the actual bid and offer automatically? I'm trying to fetch them via the lightstreamer with node.js but the documentation about that it's a little confusing. 

 

This is my node.js code.


var ls = require('lightstreamer-client');
var lsClient = new ls.LightstreamerClient("https://push.cityindex.com/","STREAMINGALL");  
lsClient.connectionDetails.setUser("XXXXXXX");
lsClient.connectionDetails.setPassword("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
lsClient.connect();


marketID = 401484415;


lsClient.addListener({
  onStatusChange: function(newStatus) {         
    console.log(newStatus);
  },
  onServerError: function(errorCode, errorMessage){
    console.log(errorMessage);
    console.log(errorCode);

  }
});

lsClient.connect();
var start = new Date()
var end = new Date()
var mySubscription = new ls.Subscription("MERGE",["PRICE." + marketID], ["Ask","TickDate", "Bid"]);
mySubscription.setDataAdapter("PRICES");
mySubscription.setRequestedSnapshot("yes");
/*lsClient.subscribe(mySubscription);*/

mySubscription.addListener({
  onSubscription: function() {
    console.log("SUBSCRIBED");
  },
  onUnsubscription: function() {
    console.log("UNSUBSCRIBED");
  },
  onItemUpdate: function(obj) {
  console.log(obj);

}});
   

lsClient.subscribe(mySubscription);

and this is the response I get:

 

{
  py: 1,
  oy: 'PRICE.401484415',
  hu: false,
  ja: {
    Xb: null,
    xb: 3,
    list: [ 'Ask', 'TickDate', 'Bid' ],
    Vs: { Ask: 1, TickDate: 2, Bid: 3 }
  },
  Pd: [
    1,
    1,
    null,
    '\\/Date(1566165701858)\\/',
    '19.64853',
    Gc: [ 2, 3 ],
    Go: { '2': true }
  ]
}

If you or any other can Help me in how to interpret this response. or how to get Bid and Offer price. I would apreciate that. 

 

thanks in advance

Share this post


Link to post

Hi James,

It looks as though you have pasted the response for the few times when your trade is accepted rather than the response when you received a red card?

When an error in placing a trade/order occurs, the OrderStatusReason code normally provides enough information to figure out what went wrong. As an example, I just now tried placing a trade using a test account with insufficient funds to cover the trade. The trade response I received is:

{"Status":2,"StatusReason":75,"OrderId":0,"Orders":[{"OrderId":0,"StatusReason":63,"Status":10,"OrderTypeId":1,"Price":0.0,"Quantity":1000000.0,"TriggerPrice":0.0,"CommissionCharge":0.0,"IfDone":[],"GuaranteedPremium":0.0,"OCO":null,"AssociatedOrders":{"Stop":null,"Limit":null},"Associated":false}],"Quote":null,"Actions":[],"ErrorMessage":null}

 

Looking up the OrderStatusReason code of 63 (underlined in bold), shows the message "Insufficient Funds". If you could post the response you receive for when a red card happens that will help us determine what the issue is. Many thanks.

Kind Regards, PM

Share this post


Link to post

I will paste the red card response shortly.  Do you think there is any more that can be done to establish why the stop and limit are not present in the response I did post?

Share this post


Link to post

Hi @Fquero47,

The relevant part of the response I have highlighted below.

image.png

1) null: You are receiving "null" as the ask price. I believe this is because we use "OFFER" instead of "ASK" for the price at which you can buy. If you change the code in your request to OFFER that should resolve the issue of the offer price being returned as Null.

2) \\/Date(1566165701858)\\/: this is the date and time in UNIX format. You'll need to run a UNIX time to human date/time conversion to see the date in a format that we'd understand. I've just run a conversion on this particular date/time and it was: GMT: Sunday, August 18, 2019 10:01:41.858 PM

3) 19.64853: the Bid price for the market you are interested in (USD/MXN).

Kind Regards, PM

Share this post


Link to post

Hi James,

Your intuition that the stop / limit orders to the trade request might be causing the problem could be right. Not sure why though. I think seeing the OrderStatusResponse code will definitely help.

For reference a response for when a trade with attached stop/limit placed successfully should appear as:

{
    "Status": 1,
    "StatusReason": 1,
    "OrderId": 693599336,
    "Orders": [
        {
            "OrderId": 693599336,
            "StatusReason": 1,
            "Status": 3,
            "OrderTypeId": 1,
            "Price": 1.21237,
            "Quantity": 1000,
            "TriggerPrice": 0,
            "CommissionCharge": 0,
            "IfDone": [
                {
                    "Stop": {
                        "OrderId": 693599338,
                        "StatusReason": 1,
                        "Status": 2,
                        "OrderTypeId": 2,
                        "Price": 0,
                        "Quantity": 1000,
                        "TriggerPrice": 1.20737,
                        "CommissionCharge": 0,
                        "IfDone": [],
                        "GuaranteedPremium": 0,
                        "OCO": null,
                        "AssociatedOrders": {
                            "Stop": null,
                            "Limit": null
                        },
                        "Associated": false
                    },
                    "Limit": {
                        "OrderId": 693599337,
                        "StatusReason": 1,
                        "Status": 2,
                        "OrderTypeId": 3,
                        "Price": 0,
                        "Quantity": 1000,
                        "TriggerPrice": 1.21737,
                        "CommissionCharge": 0,
                        "IfDone": [],
                        "GuaranteedPremium": 0,
                        "OCO": null,
                        "AssociatedOrders": {
                            "Stop": null,
                            "Limit": null
                        },
                        "Associated": false
                    }
                }
            ],
            "GuaranteedPremium": 0,
            "OCO": null,
            "AssociatedOrders": {
                "Stop": null,
                "Limit": null
            },
            "Associated": false
        }
    ],
    "Quote": null,
    "Actions": [
        {
            "ActionedOrderId": 0,
            "ActioningOrderId": 0,
            "Quantity": 1000,
            "ProfitAndLoss": 0,
            "ProfitAndLossCurrency": null,
            "OrderActionTypeId": 1
        }
    ],
    "ErrorMessage": null
}

Share this post


Link to post

The orderStatusResponse was included in the post along with the request I was sending. I will add it again here:

The request is accepted. The position is opened. However, the stop and limit portion of the request is not present in the reply or on the position when viewed on the platform. What do I need to do differently to get the stop / limit to work?

 

{
  "Status": 1,
  "StatusReason": 1,
  "OrderId": 693438627,
  "Orders": [
    {
      "OrderId": 693438627,
      "StatusReason": 1,
      "Status": 3,
      "OrderTypeId": 1,
      "Price": 1511.58,
      "Quantity": 1,
      "TriggerPrice": 0,
      "CommissionCharge": 0,
      "IfDone": [],
      "GuaranteedPremium": 0,
      "OCO": null,
      "AssociatedOrders": {
        "Stop": null,
        "Limit": null
      },
      "Associated": false
    }
  ],
  "Quote": null,
  "Actions": [
    {
      "ActionedOrderId": 0,
      "ActioningOrderId": 0,
      "Quantity": 1,
      "ProfitAndLoss": 0,
      "ProfitAndLossCurrency": null,
      "OrderActionTypeId": 1
    }
  ],
  "ErrorMessage": null
}

Share this post


Link to post

I have re-examined the red card scenario. The root of my confusion was down to an error in OrderStatusResponse lookups - I was seeing the InstructionStatusResponse on screen twice rather than seeing both of them.  It looks like I am getting an "Price Tolerance Exceeded" error.

 

I still have some questions around stop / limit, but I also realize this topic has strayed and gotten very confusing. I'm going to open a new thread for those. Thank you for all the help!

Edited by james

Share this post


Link to post

Hi James,

A "Price Tolerance Exceeded" should be quite rare as by default all our markets are set with Price Tolerance = 2, unless you manually over-ride it to another value.

Price Tolerance is essentially how much slippage you are willing to tolerate to get a trade done. The default value of 2 means the market can move up to 2 points against you from the time your order was sent to the time it's received at our servers and the trade will still execute. Should the market move greater than 2 points then the trade is rejected with the "Price Tolerance Exceeded" error message. 

I don't recall spot gold moving particularly sharply last week? Are you still receiving a lot of red card error messages? Did you previously send in a trade request call with a Price Tolerance value = 0, which would override the default value?

If you are using a value of 0, then the number of times you get a price tolerance exceeded rejection would naturally be more common.

Kind Regards, PM

Share this post


Link to post
Quote

Did you previously send in a trade request call with a Price Tolerance value = 0, which would override the default value?

I may well have done this in the course of exploring the api. 

The information about Price Tolerance is very appreciated, I misunderstood how that worked. I set Price Tolerance to 2 in my requests, and have not seen a red card since.

If I understand you correctly, setting this on any given trade will set that value as a default on subsequent trades, unless overwritten? If so, I should be set on this front.

Thank you!

Share this post


Link to post

Hi James,

Not quite. Price Tolerance is by default set as 2 for every market we offer. 

It will only change if the user (you) manually over-ride it, and it is on a per-market basis. So for instance, if you over-ride to 0 for XAUUSD, it applies to only this market. Any other market is still set as 2 unless you over-ride it when you send a call to place a trade/order on another market such as EURUSD for example. 

Good to hear you are no longer getting red cards with your test trades. We're making progress. :)

Kind Regards, PM

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×