GNU doesn’t update after adding new logic for coreML /u/xUaScalp Python Education

Trying to convert code from Python to Swift or keep Python and add small logic from Swift , to point is fetch market data over FIXAPI protocol ( 5201 ) from broker into trained model , which works fine in Swift but only for manual input for now .

Here is Python code which I glued together with help of AI , it connect and receive message and identify Bid/Ask in terminal but don’t pass it into GNU and MLmodel doesn’t seem to execute prediction either .

import json

import threading

import coremltools as ct

import numpy as np

import tkinter as tk

from tkinter import messagebox

from twisted.internet import reactor

from twisted.internet import defer

from ctrader_fix import *

import multiprocessing

# Global variables to store prices

bid_price = None

ask_price = None

lock = threading.Lock() # Lock for thread safety

# Load the CoreML model

def load_model():

try:

model = ct.models.MLModel(‘DailyEURUSDClose.mlmodel’) # Load your Core ML model

print(“Model loaded successfully.”)

return model

except Exception as e:

print(f”Error loading model: {e}”)

return None

# Predict the closing price using Bid as ‘Open’ feature

def predict_price(bid, model):

if model is None:

print(“Model is not loaded. Cannot predict price.”)

return None

input_dict = {‘Open’: float(bid)} # Use Bid price as ‘Open’ for prediction

try:

output = model.predict(input_dict)

predicted_close = output[‘Close’] # Assuming ‘Close’ is the name of the output in your model

return predicted_close

except KeyError as e:

print(f”Error: Model output does not contain the expected key ‘Close’. Available keys: {output.keys()}”)

return None

except Exception as e:

print(f”Error during prediction: {e}”)

return None

# Tkinter GUI setup

def create_gui():

global bid_price, ask_price, model

root = tk.Tk()

root.title(“Market Data & Prediction”)

# Label for showing bid and ask prices

label = tk.Label(root, text=”Market Data”, font=(“Helvetica”, 16))

label.pack(pady=10)

# Bid and Ask Price Labels

bid_label = tk.Label(root, text=”Bid: N/A”, font=(“Helvetica”, 12))

bid_label.pack(pady=5)

ask_label = tk.Label(root, text=”Ask: N/A”, font=(“Helvetica”, 12))

ask_label.pack(pady=5)

# Predicted Close Price Label

predicted_label = tk.Label(root, text=”Predicted Close: N/A”, font=(“Helvetica”, 12))

predicted_label.pack(pady=10)

# Function to update the GUI with bid, ask prices, and prediction

def update_gui():

global bid_price, ask_price

print(“Updating GUI…”) # Debugging line to check if this function is called

with lock: # Ensure thread-safe access to global variables

try:

if bid_price is not None:

bid_label.config(text=f”Bid: {bid_price:.5f}”)

else:

bid_label.config(text=”Bid: N/A”)

if ask_price is not None:

ask_label.config(text=f”Ask: {ask_price:.5f}”)

else:

ask_label.config(text=”Ask: N/A”)

# If we have the Bid price, make a prediction

if bid_price is not None:

predicted_close = predict_price(bid_price, model)

if predicted_close is not None:

predicted_label.config(text=f”Predicted Close: {predicted_close:.4f}”)

else:

predicted_label.config(text=”Predicted Close: Error”)

else:

predicted_label.config(text=”Predicted Close: N/A”)

except Exception as e:

print(f”Error during GUI update: {e}”)

root.after(1000, update_gui) # Update every second

# Start the Tkinter GUI loop

update_gui()

root.mainloop()

# Callback for when a message is received

def onMessageReceived(client, responseMessage):

global bid_price, ask_price

# Log the full response message for analysis

raw_message = responseMessage.getMessage().replace(“”, “|”)

print(f”Received full message: {raw_message}”)

messageType = responseMessage.getFieldValue(35)

if messageType == “A”:

print(“Logon successful!”)

requestMarketData(client)

elif messageType == “W”:

symbol = responseMessage.getFieldValue(55) # Symbol (e.g., EUR/USD)

print(f”Market data response for symbol: {symbol}”)

# Extracting bid and ask prices from tag 270 based on price comparison

bid_price_local = None

ask_price_local = None

# Check the number of entries (should be 2)

num_entries = int(responseMessage.getFieldValue(268)) # Number of market data entries

print(f”Number of market data entries: {num_entries}”)

prices = []

# Loop over all instances of tag 270 and collect prices

for i in range(num_entries):

price = responseMessage.getFieldValue(270)[i] # Get the i-th value for tag 270

prices.append(float(price)) # Convert to float

# Ensure we have exactly two prices (bid and ask)

if len(prices) == 2:

bid_price_local = min(prices)

ask_price_local = max(prices)

else:

print(“Unexpected number of price entries.”)

# Set global prices for the GUI in a thread-safe manner

with lock:

bid_price = bid_price_local

ask_price = ask_price_local

# Output the results (logging for now)

print(f”Market Data for {symbol}:”)

print(f” Bid: {bid_price}”)

print(f” Ask: {ask_price}”)

elif messageType == “Y”:

print(f”Error Message Received: {raw_message}”)

# Callback for client disconnection

def disconnected(client, reason):

print(f”Disconnected, reason: {reason}”)

# Callback for client connection

def connected(client):

print(“Connected to FIX server!”)

logonRequest = LogonRequest(config) # Create a logon request using the config

client.send(logonRequest)

print(“Logon request sent.”)

# Function to request market data for EUR/USD

def requestMarketData(client):

# Create a market data request

marketDataRequest = MarketDataRequest(config)

# Set the required fields for the market data request

marketDataRequest.MDReqID = “EURUSD_MarketData” # Unique request ID

marketDataRequest.SubscriptionRequestType = “1” # 1 = Snapshot + Updates

marketDataRequest.MarketDepth = “1” # Depth of market

marketDataRequest.NoMDEntryTypes = “1” # Number of MD entry types

marketDataRequest.MDEntryType = “0” # 0 = Bid, 1 = Offer

marketDataRequest.NoRelatedSym = “1” # Number of related symbols

marketDataRequest.Symbol = “1” # Symbol ID (numeric value for EUR/USD)

client.send(marketDataRequest)

print(“Market data request sent for EUR/USD”)

# Load configuration

with open(“config.json”) as configFile:

config = json.load(configFile)

print(“Config loaded:”, config)

# Create the FIX client with the provided configuration

client = Client(config[“Host”], config[“Port”], ssl=config[“SSL”])

# Load the ML model

model = load_model()

# Set the client callbacks

client.setConnectedCallback(connected)

client.setDisconnectedCallback(disconnected)

client.setMessageReceivedCallback(onMessageReceived)

# Starting the client service in a separate process

def start_client_service():

print(“Starting client service…”)

client.startService()

reactor.run()

# Run the Twisted reactor in a separate process

if __name__ == “__main__”:

client_process = multiprocessing.Process(target=start_client_service)

client_process.daemon = True

client_process.start()

# Run the Tkinter GUI in the main thread

create_gui()

submitted by /u/xUaScalp
[link] [comments]

​r/learnpython Trying to convert code from Python to Swift or keep Python and add small logic from Swift , to point is fetch market data over FIXAPI protocol ( 5201 ) from broker into trained model , which works fine in Swift but only for manual input for now . Here is Python code which I glued together with help of AI , it connect and receive message and identify Bid/Ask in terminal but don’t pass it into GNU and MLmodel doesn’t seem to execute prediction either . import json import threading import coremltools as ct import numpy as np import tkinter as tk from tkinter import messagebox from twisted.internet import reactor from twisted.internet import defer from ctrader_fix import * import multiprocessing # Global variables to store prices bid_price = None ask_price = None lock = threading.Lock() # Lock for thread safety # Load the CoreML model def load_model(): try: model = ct.models.MLModel(‘DailyEURUSDClose.mlmodel’) # Load your Core ML model print(“Model loaded successfully.”) return model except Exception as e: print(f”Error loading model: {e}”) return None # Predict the closing price using Bid as ‘Open’ feature def predict_price(bid, model): if model is None: print(“Model is not loaded. Cannot predict price.”) return None input_dict = {‘Open’: float(bid)} # Use Bid price as ‘Open’ for prediction try: output = model.predict(input_dict) predicted_close = output[‘Close’] # Assuming ‘Close’ is the name of the output in your model return predicted_close except KeyError as e: print(f”Error: Model output does not contain the expected key ‘Close’. Available keys: {output.keys()}”) return None except Exception as e: print(f”Error during prediction: {e}”) return None # Tkinter GUI setup def create_gui(): global bid_price, ask_price, model root = tk.Tk() root.title(“Market Data & Prediction”) # Label for showing bid and ask prices label = tk.Label(root, text=”Market Data”, font=(“Helvetica”, 16)) label.pack(pady=10) # Bid and Ask Price Labels bid_label = tk.Label(root, text=”Bid: N/A”, font=(“Helvetica”, 12)) bid_label.pack(pady=5) ask_label = tk.Label(root, text=”Ask: N/A”, font=(“Helvetica”, 12)) ask_label.pack(pady=5) # Predicted Close Price Label predicted_label = tk.Label(root, text=”Predicted Close: N/A”, font=(“Helvetica”, 12)) predicted_label.pack(pady=10) # Function to update the GUI with bid, ask prices, and prediction def update_gui(): global bid_price, ask_price print(“Updating GUI…”) # Debugging line to check if this function is called with lock: # Ensure thread-safe access to global variables try: if bid_price is not None: bid_label.config(text=f”Bid: {bid_price:.5f}”) else: bid_label.config(text=”Bid: N/A”) if ask_price is not None: ask_label.config(text=f”Ask: {ask_price:.5f}”) else: ask_label.config(text=”Ask: N/A”) # If we have the Bid price, make a prediction if bid_price is not None: predicted_close = predict_price(bid_price, model) if predicted_close is not None: predicted_label.config(text=f”Predicted Close: {predicted_close:.4f}”) else: predicted_label.config(text=”Predicted Close: Error”) else: predicted_label.config(text=”Predicted Close: N/A”) except Exception as e: print(f”Error during GUI update: {e}”) root.after(1000, update_gui) # Update every second # Start the Tkinter GUI loop update_gui() root.mainloop() # Callback for when a message is received def onMessageReceived(client, responseMessage): global bid_price, ask_price # Log the full response message for analysis raw_message = responseMessage.getMessage().replace(“”, “|”) print(f”Received full message: {raw_message}”) messageType = responseMessage.getFieldValue(35) if messageType == “A”: print(“Logon successful!”) requestMarketData(client) elif messageType == “W”: symbol = responseMessage.getFieldValue(55) # Symbol (e.g., EUR/USD) print(f”Market data response for symbol: {symbol}”) # Extracting bid and ask prices from tag 270 based on price comparison bid_price_local = None ask_price_local = None # Check the number of entries (should be 2) num_entries = int(responseMessage.getFieldValue(268)) # Number of market data entries print(f”Number of market data entries: {num_entries}”) prices = [] # Loop over all instances of tag 270 and collect prices for i in range(num_entries): price = responseMessage.getFieldValue(270)[i] # Get the i-th value for tag 270 prices.append(float(price)) # Convert to float # Ensure we have exactly two prices (bid and ask) if len(prices) == 2: bid_price_local = min(prices) ask_price_local = max(prices) else: print(“Unexpected number of price entries.”) # Set global prices for the GUI in a thread-safe manner with lock: bid_price = bid_price_local ask_price = ask_price_local # Output the results (logging for now) print(f”Market Data for {symbol}:”) print(f” Bid: {bid_price}”) print(f” Ask: {ask_price}”) elif messageType == “Y”: print(f”Error Message Received: {raw_message}”) # Callback for client disconnection def disconnected(client, reason): print(f”Disconnected, reason: {reason}”) # Callback for client connection def connected(client): print(“Connected to FIX server!”) logonRequest = LogonRequest(config) # Create a logon request using the config client.send(logonRequest) print(“Logon request sent.”) # Function to request market data for EUR/USD def requestMarketData(client): # Create a market data request marketDataRequest = MarketDataRequest(config) # Set the required fields for the market data request marketDataRequest.MDReqID = “EURUSD_MarketData” # Unique request ID marketDataRequest.SubscriptionRequestType = “1” # 1 = Snapshot + Updates marketDataRequest.MarketDepth = “1” # Depth of market marketDataRequest.NoMDEntryTypes = “1” # Number of MD entry types marketDataRequest.MDEntryType = “0” # 0 = Bid, 1 = Offer marketDataRequest.NoRelatedSym = “1” # Number of related symbols marketDataRequest.Symbol = “1” # Symbol ID (numeric value for EUR/USD) client.send(marketDataRequest) print(“Market data request sent for EUR/USD”) # Load configuration with open(“config.json”) as configFile: config = json.load(configFile) print(“Config loaded:”, config) # Create the FIX client with the provided configuration client = Client(config[“Host”], config[“Port”], ssl=config[“SSL”]) # Load the ML model model = load_model() # Set the client callbacks client.setConnectedCallback(connected) client.setDisconnectedCallback(disconnected) client.setMessageReceivedCallback(onMessageReceived) # Starting the client service in a separate process def start_client_service(): print(“Starting client service…”) client.startService() reactor.run() # Run the Twisted reactor in a separate process if __name__ == “__main__”: client_process = multiprocessing.Process(target=start_client_service) client_process.daemon = True client_process.start() # Run the Tkinter GUI in the main thread create_gui() submitted by /u/xUaScalp [link] [comments] 

Trying to convert code from Python to Swift or keep Python and add small logic from Swift , to point is fetch market data over FIXAPI protocol ( 5201 ) from broker into trained model , which works fine in Swift but only for manual input for now .

Here is Python code which I glued together with help of AI , it connect and receive message and identify Bid/Ask in terminal but don’t pass it into GNU and MLmodel doesn’t seem to execute prediction either .

import json

import threading

import coremltools as ct

import numpy as np

import tkinter as tk

from tkinter import messagebox

from twisted.internet import reactor

from twisted.internet import defer

from ctrader_fix import *

import multiprocessing

# Global variables to store prices

bid_price = None

ask_price = None

lock = threading.Lock() # Lock for thread safety

# Load the CoreML model

def load_model():

try:

model = ct.models.MLModel(‘DailyEURUSDClose.mlmodel’) # Load your Core ML model

print(“Model loaded successfully.”)

return model

except Exception as e:

print(f”Error loading model: {e}”)

return None

# Predict the closing price using Bid as ‘Open’ feature

def predict_price(bid, model):

if model is None:

print(“Model is not loaded. Cannot predict price.”)

return None

input_dict = {‘Open’: float(bid)} # Use Bid price as ‘Open’ for prediction

try:

output = model.predict(input_dict)

predicted_close = output[‘Close’] # Assuming ‘Close’ is the name of the output in your model

return predicted_close

except KeyError as e:

print(f”Error: Model output does not contain the expected key ‘Close’. Available keys: {output.keys()}”)

return None

except Exception as e:

print(f”Error during prediction: {e}”)

return None

# Tkinter GUI setup

def create_gui():

global bid_price, ask_price, model

root = tk.Tk()

root.title(“Market Data & Prediction”)

# Label for showing bid and ask prices

label = tk.Label(root, text=”Market Data”, font=(“Helvetica”, 16))

label.pack(pady=10)

# Bid and Ask Price Labels

bid_label = tk.Label(root, text=”Bid: N/A”, font=(“Helvetica”, 12))

bid_label.pack(pady=5)

ask_label = tk.Label(root, text=”Ask: N/A”, font=(“Helvetica”, 12))

ask_label.pack(pady=5)

# Predicted Close Price Label

predicted_label = tk.Label(root, text=”Predicted Close: N/A”, font=(“Helvetica”, 12))

predicted_label.pack(pady=10)

# Function to update the GUI with bid, ask prices, and prediction

def update_gui():

global bid_price, ask_price

print(“Updating GUI…”) # Debugging line to check if this function is called

with lock: # Ensure thread-safe access to global variables

try:

if bid_price is not None:

bid_label.config(text=f”Bid: {bid_price:.5f}”)

else:

bid_label.config(text=”Bid: N/A”)

if ask_price is not None:

ask_label.config(text=f”Ask: {ask_price:.5f}”)

else:

ask_label.config(text=”Ask: N/A”)

# If we have the Bid price, make a prediction

if bid_price is not None:

predicted_close = predict_price(bid_price, model)

if predicted_close is not None:

predicted_label.config(text=f”Predicted Close: {predicted_close:.4f}”)

else:

predicted_label.config(text=”Predicted Close: Error”)

else:

predicted_label.config(text=”Predicted Close: N/A”)

except Exception as e:

print(f”Error during GUI update: {e}”)

root.after(1000, update_gui) # Update every second

# Start the Tkinter GUI loop

update_gui()

root.mainloop()

# Callback for when a message is received

def onMessageReceived(client, responseMessage):

global bid_price, ask_price

# Log the full response message for analysis

raw_message = responseMessage.getMessage().replace(“”, “|”)

print(f”Received full message: {raw_message}”)

messageType = responseMessage.getFieldValue(35)

if messageType == “A”:

print(“Logon successful!”)

requestMarketData(client)

elif messageType == “W”:

symbol = responseMessage.getFieldValue(55) # Symbol (e.g., EUR/USD)

print(f”Market data response for symbol: {symbol}”)

# Extracting bid and ask prices from tag 270 based on price comparison

bid_price_local = None

ask_price_local = None

# Check the number of entries (should be 2)

num_entries = int(responseMessage.getFieldValue(268)) # Number of market data entries

print(f”Number of market data entries: {num_entries}”)

prices = []

# Loop over all instances of tag 270 and collect prices

for i in range(num_entries):

price = responseMessage.getFieldValue(270)[i] # Get the i-th value for tag 270

prices.append(float(price)) # Convert to float

# Ensure we have exactly two prices (bid and ask)

if len(prices) == 2:

bid_price_local = min(prices)

ask_price_local = max(prices)

else:

print(“Unexpected number of price entries.”)

# Set global prices for the GUI in a thread-safe manner

with lock:

bid_price = bid_price_local

ask_price = ask_price_local

# Output the results (logging for now)

print(f”Market Data for {symbol}:”)

print(f” Bid: {bid_price}”)

print(f” Ask: {ask_price}”)

elif messageType == “Y”:

print(f”Error Message Received: {raw_message}”)

# Callback for client disconnection

def disconnected(client, reason):

print(f”Disconnected, reason: {reason}”)

# Callback for client connection

def connected(client):

print(“Connected to FIX server!”)

logonRequest = LogonRequest(config) # Create a logon request using the config

client.send(logonRequest)

print(“Logon request sent.”)

# Function to request market data for EUR/USD

def requestMarketData(client):

# Create a market data request

marketDataRequest = MarketDataRequest(config)

# Set the required fields for the market data request

marketDataRequest.MDReqID = “EURUSD_MarketData” # Unique request ID

marketDataRequest.SubscriptionRequestType = “1” # 1 = Snapshot + Updates

marketDataRequest.MarketDepth = “1” # Depth of market

marketDataRequest.NoMDEntryTypes = “1” # Number of MD entry types

marketDataRequest.MDEntryType = “0” # 0 = Bid, 1 = Offer

marketDataRequest.NoRelatedSym = “1” # Number of related symbols

marketDataRequest.Symbol = “1” # Symbol ID (numeric value for EUR/USD)

client.send(marketDataRequest)

print(“Market data request sent for EUR/USD”)

# Load configuration

with open(“config.json”) as configFile:

config = json.load(configFile)

print(“Config loaded:”, config)

# Create the FIX client with the provided configuration

client = Client(config[“Host”], config[“Port”], ssl=config[“SSL”])

# Load the ML model

model = load_model()

# Set the client callbacks

client.setConnectedCallback(connected)

client.setDisconnectedCallback(disconnected)

client.setMessageReceivedCallback(onMessageReceived)

# Starting the client service in a separate process

def start_client_service():

print(“Starting client service…”)

client.startService()

reactor.run()

# Run the Twisted reactor in a separate process

if __name__ == “__main__”:

client_process = multiprocessing.Process(target=start_client_service)

client_process.daemon = True

client_process.start()

# Run the Tkinter GUI in the main thread

create_gui()

submitted by /u/xUaScalp
[link] [comments] 

Leave a Reply

Your email address will not be published. Required fields are marked *