ejtraderlabs / ejtraderct Goto Github PK
View Code? Open in Web Editor NEWThe best Python Ctrader FIX API Perfect for HFT
License: MIT License
The best Python Ctrader FIX API Perfect for HFT
License: MIT License
ejtraderCT is really easy to use, is there any possibility to use it in REST API?
For instance, TradingView's alert triggers the webhook, and we have a Python Flask application(RESTFUL API) to receive this call, and then use ejtraderCT to open/close the position.
when i try get history with this method;
history = api.history("GBPUSD", "H1", int(datetime.datetime.now().timestamp()) - 10000)
i got error;
AttributeError: 'Ctrader' object has no attribute 'api'
there is no api defination in the class
Hi,
After executing two consecutive trades using BUY and SELL Market types the next ones cannot be executed the log says it were executed but they aren't.
For example
i open a Buy order and then i try to close it using the method close_all() everything works fine. (I use this method because the close position by id doesn't work at all).
After that first successful execution if i try to open another one (in the same session) the new buy order executes correctly but if i try to use again the close_all method the buy order still persists in the market.
Another scenery is:
I can open many buy market orders but i cannot close them (using the close all method).
my implementations:
Buy ORDER
if not self.api.isconnected():
raise CTraderDisconnected("CTrader is not connected")
try:
logger.info(f"🕦 Buying ${order.quantity} from {order.symbol}")
price = self.api.quote()
logger.info(f"Quote: {price=}")
price = price[order.symbol]["bid"]
symbol = order.symbol
volume = order.quantity
stop_loss = 0
take_profit = 0
oid = self.api.buy(symbol=symbol, volume=volume, stoploss=stop_loss, takeprofit=take_profit)
logger.info(f"CTrader Position {oid}")
Close all:
positions = self.api.positions()
if len(positions) < 1:
break
logger.info(positions)
self.api.close_all()
time.sleep(5)
Sometimes, the second try produces an unexpected infinite loop with a number of 16 digits.
I have some thoughts on what might be going on, but I need to test and debug those ideas when the market opens with a demo account.
Cheers
Hello, first of all thank you so much for programming this library.
i've tried it weeks ago and was working fine with my broker but today stopped to work
is that a problem from broker or the library needs to be updated?
i want to subscribe to a symbol but isn't subscribing and i get a message:
i'm using the exact code example provided in your readme.md
api.subscribe("USTEC")
api.quote("USTEC")
but not working neither my real nor demo account.
Can you help me?
cheers.
Hello ejtraderCT Team,
I am experiencing an issue with the close_all method in the Ctrader class, which is not functioning as expected in my implementation. The method is supposed to close all open positions, but it fails to do so. Here's the relevant snippet from my main.py:
python code
def process_close_all():
# ... code to update and log current positions ...
update_positions_list()
current_positions = api.positions()
ctrader.close_all()
time.sleep(1)
# ... logging message ...
Despite calling ctrader.close_all(), the positions remain open. The close_all method is invoked after retrieving the current positions, but the subsequent positions check reveals that they are not closed. This issue occurs even though there are active positions present.
Could you please help me understand if there's a known issue with this method or if I might be missing something in my implementation? Any guidance or suggestions for troubleshooting this would be greatly appreciated.
Thank you for your assistance.
"ERROR:root:Logged out: Can't route request
ERROR:root:Logged out: Can't route request
ERROR:root:Disconnected
ERROR:root:Disconnected"
FIX_SERVER="h51.p.ctrader.com"
FIX_BROKER="icmarkets"
FIX_LOGIN="8337657"
FIX_PASSWORD="KDCG2008"
FIX_CURRENCY="USD"
FIX API information from ctrader web:
"Host name: h51.p.ctrader.com
(Current IP address 176.58.118.184 can be changed without notice)
Port: 5211 (SSL), 5201 (Plain text).
Password: (a/c 8337657 password)
SenderCompID: demo.icmarkets.8337657
TargetCompID: CSERVER
SenderSubID: QUOTE
Host name: h51.p.ctrader.com
(Current IP address 176.58.118.184 can be changed without notice)
Port: 5212 (SSL), 5202 (Plain text).
Password: (a/c 8337657 password)
SenderCompID: demo.icmarkets.8337657
TargetCompID: CSERVER
SenderSubID: TRADE"
I've been playing with the Python API Class, and managed to connect to my broker Pepperstone, however, my first real test is to list open positions, so I've enabled "DEBUG" logging, and used the sample code
positions = api.positions()
print(positions)
Watching the debug code the correct data is in debug logging, however the returned value is []
So then I used Thonny to step through the code, and if I step through my code, the correct data is returned and printed, however if I let the debugger simply run past the code, not result is returned.
Using Python 3.10.6 if it makes any difference.
Thanks.
In the context of algorithmic trading, I've noticed that I receive a 'Symbol not Subscribed' alert when attempting to get quotes for a specific symbol (e.g., EURUSD) when there are no open positions for that pair. Is there a way to subscribe to a symbol and receive quotes even in the absence of open positions? What approach should be taken to ensure the availability of quotes for any given symbol?
I'm having no response when I'm running the Ctrader (from ejtraderCT import Ctrader). i tried to put a wrong password and the same...
Any suggestion?
symbol = "EURUSD"
volume = 1 # position size:
stoploss = round(price - 0.00010, 6)
takeprofit = round(price + 0.00020, 6)
id = api.sell(symbol, volume, stoploss, takeprofit)
Thanks for this python package.
I was wondering if someone can tell me what I'm doing wrong.
from ejtraderCT import Ctrader
import time
import logging
logging.getLogger().setLevel(logging.INFO)
SERVER="demo1.p.ctrader.com"
LOGIN="demo.purpletradingprop.12346679"
PASSWORD="XXX"
CURRENCY="USD"
api = Ctrader(server=SERVER, account=LOGIN, password=PASSWORD, currency=CURRENCY, debug=True)
checkConnection = api.isconnected()
print("Is Connected?: ", checkConnection)
time.sleep(1)
quote = api.quote()
print(quote)
My output:
INFO:root:Market is Close or Disconnected 'NoneType' object is not callable
INFO:root:Market is Close or Logged out 'NoneType' object is not callable
Thanks for the help.
I tested also Python 3.9 but I have the same problem
Hi, I'm using pepperstone for this and having problem logging in. Can you please point me to the right direction?
Using these credentials:
Host name: h58.p.ctrader.com
(Current IP address 84.22.97.147 can be changed without notice)
Port: 5212 (SSL), 5202 (Plain text).
Password: (a/c 4055947 password)
SenderCompID: demo.pepperstone.4055947
TargetCompID: cServer
SenderSubID: TRADE
ejtrader.py
from ejtraderCT import Ctrader
import time
import logging
from datetime import datetime
logging.getLogger().setLevel(logging.DEBUG)
server = "h58.p.ctrader.com" # Host name
broker = "demo.pepperstone"
account = "4055947"
password = "abc1234"
currency = "USD"
api = Ctrader(server, broker, account, password, currency)
But get this error:
python3 ejtrader.py
DEBUG:root:SEND >>> 8=FIX.4.4|9=124|35=A|49=demo.pepperstone.4055947|50=QUOTE|56=CSERVER|57=QUOTE|34=1|52=20220828-07:15:28|98=0|108=30|553=4055947|554=abc1234|10=050|
DEBUG:root:SEND >>> 8=FIX.4.4|9=124|35=A|49=demo.pepperstone.4055947|50=TRADE|56=CSERVER|57=TRADE|34=1|52=20220828-07:15:28|98=0|108=30|553=4055947|554=abc1234|10=246|
DEBUG:root:SEND >>> 8=FIX.4.4|9=100|35=x|49=demo.pepperstone.4055947|50=QUOTE|56=CSERVER|57=QUOTE|34=2|52=20220828-07:15:28|320=1|559=0|10=071|
DEBUG:root:RECV <<< 8=FIX.4.4|9=113|35=5|34=1|49=CSERVER|50=QUOTE|52=20220828-07:15:28.380|56=demo.pepperstone.4055947|57=QUOTE|58=RET_NO_SUCH_LOGIN|10=183|
ERROR:root:Logged out: RET_NO_SUCH_LOGIN
ERROR:root:Disconnected
DEBUG:root:RECV <<< 8=FIX.4.4|9=113|35=5|34=1|49=CSERVER|50=TRADE|52=20220828-07:15:28.380|56=demo.pepperstone.4055947|57=TRADE|58=RET_NO_SUCH_LOGIN|10=123|
ERROR:root:Logged out: RET_NO_SUCH_LOGIN
ERROR:root:Disconnected
What am I doing wrong?
Hi Emerson,
First, thank you very much for this package, it's extremly useful!
I wanting to build a small copy trading script based on this repository, the orders will be copied from 3-5 master accounts to one salve account and i would like to know where the posistions/orders are come from.
I'm thinking about using Designation, or ClOrdId as identification
So lets say master account A will send trade with Designation = "MA1", or ClOrdId = 'MA1' +get_time()...
then api.positions(), api.orders() will response with the Designation or ClOrdId along with other informations (price, volumn etc...) and I can group them by Designation or ClOrdId
My questions are:
Thank you again :)
Hello!
I am trying to connect to my Demo FxPro account.
Settings in python file as follows
server = "h8.p.c-trader.cn" # Host name
broker = "fxpro"
account = "10552478"
password = "xxxxxx-xxxxxx-xxxxxx"
currency = "EUR"
Returning the following Error
ERROR:root:Logged out: RET_INVALID_DATA
ERROR:root:Disconnected
ERROR:root:Logged out: RET_INVALID_DATA
ERROR:root:Disconnected
Could you please take a look at this and let me know what I am doing wrong?
Thanks!
Hi,
I love this idea. Really needed it!!!
Said that, is it normal that StopLoss and TakeProfit are not implented/don't work yet?
Is it also normal that only symbols with a string length of 6 can be traded?
Thank you
it's posible to implement smem function to modify the current position and change stoploss and take profit?
Like trailing stop
Hi ejtraderCT Team,
This package is great and running well for us. However, we wanted to make it work with Flask Application. So, we can host it on the Linux server and then send a request to it to open and close the positions.
When I start my Flask Application and open 1 order. It opens the position correctly but when I try to send it again it don't process the connection and shows this error.
ERROR:root:Disconnected
ERROR:root:Disconnected
Then after few mints. It's automatically show another message and start for one more alert again.
ERROR:root:Error in QUOTE send. Closing connection. client_id: 1
ERROR:root:Error in QUOTE send. Closing connection. client_id: 1
After this above error message seems like the connection is closed and now I can make the connection again. According to my understanding. I can make the connection only once. Whenever I send a few Flask request it stops working as it's already connected to the server and our code is to make the new connection every time.
I don't know how I can change my code according to the Client Server Connection. So, don't connect again and again or check every time if it's connected or not already.
`class Exchanges:
def ctrader(key, secret, password, broker, pair, ordertype, order, volume, price, sl, tp):
SERVER = secret # 'h50.p.ctrader.com'
BROKER = broker # 'demo.icmarkets'
LOGIN = key #account_number
PASSWORD = password #password
CURRENCY = pair[-3:] #'USD'
def auth():
logging.getLogger().setLevel(logging.INFO)
api = Ctrader(SERVER, BROKER, LOGIN, PASSWORD, CURRENCY)
return api
try:
client = auth()
time.sleep(1)
client.subscribe(pair)
time.sleep(1)
quote = client.quote(pair)
print(quote['ask'])
if order == 'buy':
order = client.buy(pair, volume, stoploss=None, takeprofit=None)`
Please help me to resolve this. My Flask application is almost ready but I'm stuck here. Your help would be very appreciated. Also if you have a discord server let me know.
One last thing that I would like to mention about the TP and SL. We are unable to set the TP and SL as per the documentation. It would be great if you find a way to implement it. As it is very important to set the Pre to define TP and SL instead of waiting for the system to close it.
Thanks
Try to get the symbol quote, but the result is Symbol not Subscribed.
No problem with connection, but cannot get quote..
`
api = Ctrader(server, account, password)
api.subscribe("EURUSD")
price = api.quote("EURUSD")
print(price)
price = api.quote()
price = price["EURUSD"]["bid"]
symbol = "EURUSD"
volume = 0.01 # position size:
stoploss = round(price - 0.00010,6)
takeprofit = round(price + 0.00020,6)
id = api.buy(symbol, volume, stoploss, takeprofit)
print(f"Position: {id}")
price = api.quote()
price = price['EURUSD']['bid']
symbol = "EURUSD"
volume = 0.01 # position size
stoploss = round(price + 0.00010,6)
takeprofit = round(price - 0.00010,6)
id = api.sell(symbol, volume, stoploss, takeprofit)
print(f"Position: {id}")`
Its not working or it is me who is stupid)
my code:
from ejtraderCT import Ctrader
import logging
SERVER = 'h18.p.ctrader.com'
BROKER = 'demo.roboforex'
LOGIN = '6183532'
PASSWORD = 'damian999'
CURRENCY = 'EUR'
def auth():
logging.getLogger().setLevel(logging.INFO)
api = Ctrader(SERVER, BROKER, LOGIN, PASSWORD, CURRENCY)
return api
client = auth()
client.subscribe('EURUSD')
quote = client.quote('EURUSD')
print(quote)
feedback:
INFO:root:Quote logged on - client_id 1
INFO:root:Trade logged on - client_id 1
Symbol not Subscribed
if I'm doing it this way:
client.subscribe("EURUSD", "GBPUSD")
quote = client.quote()
print(quote)
do not get real time quotes anyway:
INFO:root:Quote logged on - client_id 1
INFO:root:Trade logged on - client_id 1
{}
getting just an empty {}
FIX_SERVER="h8.p.c-trader.cn"
FIX_BROKER="icmarkets"
FIX_LOGIN="3152339"
FIX_PASSWORD="393214"
FIX_CURRENCY="EUR"
hi, how can i confirm or find my Forex broker's 'FIX_SERVER' address? Thanks
I would like to call my open equity and balance? This is important for risk management prior placing an order. Please advise and than you for your contribution.
import logging
import time
from ejtraderCT import Ctrader
logging.getLogger().setLevel(logging.INFO)
SERVER = "78.129.190.32" # Host name
BROKER = "demo.icmarkets"
LOGIN = "8673704"
PASSWORD = "XXBP6072"
CURRENCY = "EUR"
api = Ctrader(server=SERVER, broker=BROKER, login=LOGIN, password=PASSWORD, currency=CURRENCY)
symbol = "EURUSD"
volume = 10 # position size
limits = 5
api.subscribe(symbol)
time.sleep(3)
# Buy position
quote = api.quote(symbol)
print(quote)
takeprofit = quote['ask'] + limits * 0.0001
api.buy(symbol=symbol, volume= volume, stoploss=None, takeprofit=takeprofit)
The order can be created, but without takeprofit... Did I do something wrong?
Thanks for your effort and looking forward to hearing from you:)
Hello, I've noticed that when I don't use the logout method in my class or Jupyter Notebook, the session with the broker persists, and you cannot log in again. As a consequence, you have to wait until it expires (in my case, up to 5 hours).
This will fix it (inside the cTrader class)
def __del__(self):
self.logout()
(i've forked the repo and created a commit for it, if this is not the right approach i won't create the PR)
Cheers.
hi, could you please explain why the following code is resulting in the 3 orders/positions you can see in the images below?
api = Ctrader(server,account,password)
api.subscribe("EURUSD")
print(api.quote())
print(api.buy(symbol="EURUSD", volume=0.01, stoploss=1, takeprofit=1.5, price=1.08))
api.logout()
moreover, the quote()
method is returning {}
when i enter the lot size at volume = 0.1
it return error (ERROR:root:Order volume 10000.00 is bigger than maxVolume=50.00.)
so when i edit the volume to :
volume = 0.00001
its create the position with 1 Lot.
any help to how can i configure this please?
by the way the symbol i trade is ETHUSD his fix api id is 22397
i have edited the Symbol.py list and added it to there like the others.
45: {'id': 22397, 'pip_position': 4, 'name': 'ETHUSD', 'bid_volume': 0, 'ask_volume': 0},
this line.
i want to configure the lot size so when i enter 0.1 Lot at volume
will open position with 0.1 Lot
help please.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.