OHLC Live data

Created at 09 Oct 2023, 06:53
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
UL

ultmnc

Joined 19.07.2023

OHLC Live data
09 Oct 2023, 06:53


Good day

 

I am looking for LIVE ohlc data, not just bid and ask data

Can you assist me with this please?

Response is sincerely appreciated

Regards


@ultmnc
Replies

PanagiotisChar
09 Oct 2023, 13:10 ( Updated at: 09 Oct 2023, 13:12 )

Hi there,

Use ProtoOASubscribeLiveTrendbarReq to subscribe to live trendbar data.


@PanagiotisChar

ultmnc
09 Oct 2023, 13:19 ( Updated at: 09 Oct 2023, 13:33 )

RE: OHLC Live data

PanagiotisChar said: 

Hi there,

Use ProtoOASubscribeLiveTrendbarReq to subscribe to live trendbar data.

Are you able to show me sample code using ProtoOASubscribeLiveTrendbarReq and ProtoOASubscribeLiveTrendbarRes with 1 second data as i am getting stuck here please

Your responses are appreciated

 

regards

 


@ultmnc

mywebsidekicks
01 Oct 2024, 13:30 ( Updated at: 01 Oct 2024, 13:36 )

I'm using this script:

 

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
import pandas as pd
import numpy as np


credentialsFile = open("credentials.json")
credentials = json.load(credentialsFile)


host = EndPoints.PROTOBUF_LIVE_HOST if credentials["HostType"].lower() == "live" else EndPoints.PROTOBUF_DEMO_HOST
client = Client(host, EndPoints.PROTOBUF_PORT, TcpProtocol)

symbolName = "EURUSD"


## Define the trendbar period variable
# trendbar_period_str = "H1"  # Set this to "D1" for daily bars or "H1" for hourly bars
trendbar_period_str = "M5"

## Map the string to the corresponding ProtoOATrendbarPeriod value
trendbar_period_map = {
    "D1": ProtoOATrendbarPeriod.D1,
    "H1": ProtoOATrendbarPeriod.H1,
    "M30": ProtoOATrendbarPeriod.M30,
    "M15": ProtoOATrendbarPeriod.M15,
    "M10": ProtoOATrendbarPeriod.M10,
    "M5": ProtoOATrendbarPeriod.M5,
}
trendbar_period = trendbar_period_map[trendbar_period_str]


## Set your desired 'from' and 'to' dates in format: Year, Month, Day
data_from = datetime.datetime(2021, 12, 27)
# data_to = datetime.datetime.utcnow()  # until today, or:
data_to = datetime.datetime(2024, 8, 20)  # any other specific date you want


dailyBars = []
symbolId = None

def connected(client):  # Callback for client connection
    print("\nConnected")
    request = ProtoOAApplicationAuthReq()
    request.clientId = credentials["ClientId"]
    request.clientSecret = credentials["Secret"]
    deferred = client.send(request)
    deferred.addCallbacks(applicationAuthResponseCallback, onError)

def applicationAuthResponseCallback(result):
    print("\nApplication authenticated")
    request = ProtoOAAccountAuthReq()
    request.ctidTraderAccountId = credentials["AccountId"]
    request.accessToken = credentials["AccessToken"]
    deferred = client.send(request)
    deferred.addCallbacks(accountAuthResponseCallback, onError)

def accountAuthResponseCallback(result):
    print("\nAccount authenticated")
    request = ProtoOASymbolsListReq()
    request.ctidTraderAccountId = credentials["AccountId"]
    request.includeArchivedSymbols = False
    deferred = client.send(request)
    deferred.addCallbacks(symbolsResponseCallback, onError)

def symbolsResponseCallback(result):
    print("\nSymbols received")
    symbols = Protobuf.extract(result)
    global symbolName, symbolId
    symbolsFilterResult = list(filter(lambda symbol: symbol.symbolName == symbolName, symbols.symbol))
    if len(symbolsFilterResult) == 0:
        raise Exception(f"There is no symbol that matches your defined symbol name: {symbolName}")
    elif len(symbolsFilterResult) > 1:
        raise Exception(f"More than one symbol matched with your defined symbol name: {symbolName}, match result: {symbolsFilterResult}")
    symbol = symbolsFilterResult[0]
    symbolId = symbol.symbolId
    print(f"SymbolID = {symbolId}")
    request = ProtoOAGetTrendbarsReq()
    request.symbolId = symbolId
    request.ctidTraderAccountId = credentials["AccountId"]
    request.period = trendbar_period
    # request.period = ProtoOATrendbarPeriod.M5
    request.fromTimestamp = int(calendar.timegm(data_from.utctimetuple())) * 1000
    request.toTimestamp = int(calendar.timegm(data_to.utctimetuple())) * 1000
    # to make sure it's unlimited
	request.count = 9999999
    deferred = client.send(request)
    deferred.addCallbacks(trendbarsResponseCallback, onError)

def trendbarsResponseCallback(result):
    print("\nTrendbars received")
    trendbars = Protobuf.extract(result)
    print(f"trendbars type {type(trendbars)}")
    # print(f"trendbars = {trendbars[0]}")
    barsData = list(map(transformTrendbar, trendbars.trendbar))
    # print(f"barsData = {barsData}")
    global dailyBars
    dailyBars.clear()
    dailyBars.extend(barsData)
    print("\ndailyBars length:", len(dailyBars))
    print("\Stopping reactor...")
    reactor.stop()

def transformTrendbar(trendbar):
    time_in_minutes = int(trendbar_period_str.replace("M", ""))
    openTime = datetime.datetime.fromtimestamp(trendbar.utcTimestampInMinutes * 60, datetime.timezone.utc)
    openPrice = (trendbar.low + trendbar.deltaOpen) / 100000.0
    highPrice = (trendbar.low + trendbar.deltaHigh) / 100000.0
    lowPrice = trendbar.low / 100000.0
    closePrice = (trendbar.low + trendbar.deltaClose) / 100000.0
    return [openTime, openPrice, highPrice, lowPrice, closePrice, trendbar.volume]


def onError(failure):  # Call back for errors
    print("\nMessage Error: ", failure)

def disconnected(client, reason):  # Callback for client disconnection
    print("\nDisconnected: ", reason)

def onMessageReceived(client, message):  # Callback for receiving all messages
    if message.payloadType in [ProtoHeartbeatEvent().payloadType, ProtoOAAccountAuthRes().payloadType,
                               ProtoOAApplicationAuthRes().payloadType, ProtoOASymbolsListRes().payloadType,
                               ProtoOAGetTrendbarsRes().payloadType]:
        return
    print("\nMessage received: \n", Protobuf.extract(message))

client.setConnectedCallback(connected)
client.setDisconnectedCallback(disconnected)
client.setMessageReceivedCallback(onMessageReceived)

client.startService()
reactor.run()


df = pd.DataFrame(np.array(dailyBars),
                  columns=['Time', 'Open', 'High', 'Low', 'Close', 'Volume'])
df["Open"] = pd.to_numeric(df["Open"])
df["High"] = pd.to_numeric(df["High"])
df["Low"] = pd.to_numeric(df["Low"])
df["Close"] = pd.to_numeric(df["Close"])
df["Volume"] = pd.to_numeric(df["Volume"])



print(df)

 

And for the “credentials.json” you obviously have to use this format:

 

{
  "ClientId": "your-client-id",
  "Secret": "your-secret",
  "AccountId": your-account-id,
  "AccessToken": "your-access-token",
  "HostType": "live"
}

 

 


@mywebsidekicks

mywebsidekicks
01 Oct 2024, 13:40 ( Updated at: 02 Oct 2024, 04:57 )

And make sure your ‘AccountId’ is one of these:

https://ctrader.com/forum/connect-api-support/42441/#post-110782


@mywebsidekicks