What am I doing wrong... can't open a trade
Created at 21 Aug 2023, 15:27
TH
What am I doing wrong... can't open a trade
21 Aug 2023, 15:27
Below is my code… Below that is the output I get… It hangs submitting the code and I don't know what I could be doing wrong. I have been able to pull candle data but not send in an order for a forex pair.
from ctrader_open_api import Client, Protobuf, TcpProtocol, EndPoints
from ctrader_open_api.messages.OpenApiCommonMessages_pb2 import *
from ctrader_open_api.messages.OpenApiMessages_pb2 import *
from ctrader_open_api.messages.OpenApiModelMessages_pb2 import *
from twisted.internet import reactor
import json
import datetime
import calendar
print("Initializing...")
# Load credentials
credentialsFile = open("credentials-dev.json")
credentials = json.load(credentialsFile)
print("Loaded credentials.")
# Set the currency pair
currency_pair = "USDJPY"
print(f"Currency pair set to: {currency_pair}")
# Create a client
host = EndPoints.PROTOBUF_LIVE_HOST if credentials["HostType"].lower() == "live" else EndPoints.PROTOBUF_DEMO_HOST
client = Client(host, EndPoints.PROTOBUF_PORT, TcpProtocol)
print("Client created.")
def sendProtoOAGetAccountListByAccessTokenReq(clientMsgId = None):
request = ProtoOAGetAccountListByAccessTokenReq()
request.accessToken = credentials["AccessToken"]
deferred = client.send(request, clientMsgId = clientMsgId)
deferred.addErrback(onError)
def sendProtoOANewOrderReq(symbolId, orderType, tradeSide, volume, price = None, clientMsgId = None):
request = ProtoOANewOrderReq()
request.ctidTraderAccountId = credentials["AccountId"]
request.symbolId = int(symbolId)
print(f"Symbol ID: {request.symbolId}")
request.orderType = ProtoOAOrderType.Value(orderType.upper())
request.tradeSide = ProtoOATradeSide.Value(tradeSide.upper())
request.volume = int(volume) * 100
print(f"Volume: {request.volume}")
print(f"Order Type: {request.orderType}")
print(f"Trade Side: {request.tradeSide}")
if request.orderType == ProtoOAOrderType.LIMIT:
request.limitPrice = float(price)
elif request.orderType == ProtoOAOrderType.STOP:
request.stopPrice = float(price)
print(f"price: {price}")
print(f"{request}")
deferred = client.send(request, clientMsgId = clientMsgId)
deferred.addErrback(onError)
def sendNewMarketOrder(symbolId, tradeSide, volume, clientMsgId = None):
sendProtoOANewOrderReq(symbolId, "MARKET", tradeSide, volume, clientMsgId = clientMsgId)
# Error handling
def onError(failure):
print("Error:", failure)
if hasattr(failure, 'value') and hasattr(failure.value, 'error'):
print("Error details:", failure.value.error)
reactor.stop()
# Callbacks
def connected(client):
print("Connected to the client.")
request = ProtoOAApplicationAuthReq()
request.clientId = credentials["ClientId"]
request.clientSecret = credentials["Secret"]
print("Sending application authentication request...")
deferred = client.send(request)
deferred.addCallbacks(applicationAuthResponseCallback, onError)
def applicationAuthResponseCallback(result):
print("Application authentication successful.")
request = ProtoOAAccountAuthReq()
request.ctidTraderAccountId = credentials["AccountId"]
request.accessToken = credentials["AccessToken"]
print("Sending account authentication request...")
deferred = client.send(request)
deferred.addCallbacks(accountAuthResponseCallback, onError)
def accountAuthResponseCallback(result):
print("Account authentication successful.")
print("Fetching symbols...")
fetchForCurrencyPair()
def fetchForCurrencyPair():
print("Fetching symbols for currency pair...")
request = ProtoOASymbolsListReq()
request.ctidTraderAccountId = credentials["AccountId"]
request.includeArchivedSymbols = False
deferred = client.send(request)
deferred.addCallbacks(symbolsResponseCallback, onError)
def symbolsResponseCallback(result):
print("Received symbols response.")
symbols = Protobuf.extract(result)
symbol_id_mapping = {symbol.symbolName: symbol.symbolId for symbol in symbols.symbol}
# Place trade for the specified currency pair
symbolId = symbol_id_mapping.get(currency_pair)
if symbolId:
print(f"Placing a BUY order for {currency_pair} with symbol ID {symbolId}...")
sendNewMarketOrder(symbolId, "BUY", 10)
else:
print(f"Symbol ID not found for currency pair: {currency_pair}")
print("Starting client service...")
client.setConnectedCallback(connected)
client.startService()
reactor.run()
This is the output I get:
Initializing...
Loaded credentials.
Currency pair set to: USDJPY
Client created.
Starting client service...
Connected to the client.
Sending application authentication request...
Application authentication successful.
Sending account authentication request...
Account authentication successful.
Fetching symbols...
Fetching symbols for currency pair...
Received symbols response.
Placing a BUY order for USDJPY with symbol ID 4...
Symbol ID: 4
Volume: 1000
Order Type: 1
Trade Side: 1
price: None
ctidTraderAccountId: 5XXXXXXXXXX
symbolId: 4
orderType: MARKET
tradeSide: BUY
volume: 1000
the.innovative214
21 Aug 2023, 16:35
It's ok now. Turns out I had the wrong volume size.
@the.innovative214