oversite_scrye/scrye/controller4.py
2023-07-08 10:09:12 -07:00

638 lines
25 KiB
Python

from pywinauto import application
from pywinauto import mouse
from pywinauto.keyboard import send_keys
import time
import cv2
import numpy as np
from scipy.signal import argrelextrema
import sqlite3
con = sqlite3.connect("oversite.db", isolation_level=None)
cur = con.cursor()
def function ptlist(mask):
intersection_points = np.where(mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
pts_list = np.array(pts_list)
pts_list = pts_list[pts_list[:,0].argsort()]
print(pts_list)
blue = {}
for coord in pts_list:
print(coord)
if coord[0] in blue:
if coord[1] > blue[coord[0]]["max"]:
blue[coord[0]]["max"] = coord[1]
if coord[1] < blue[coord[0]]["min"]:
blue[coord[0]]["min"] = coord[1]
else:
blue[coord[0]]={"max" : coord[1], "min": coord[1]}
return blue
#LIME = [(50,205,50 ), (50,205, 50)]
#LIME = [(45,190,45 ), (90,255, 209)]
LIME = [( 0,255,0), (0,255,0)]
BLACK = [(0,0,0),(0,0,0)]
BLUE = [(255,0,0),(255,0,0)]
RED = [(0,0,255),(0,0,255)]
GREEN = [(35,142,107),(35,142,107)]
WHITE = [(32,165,218),(32,165,218)]
TAN = [(179,222,245),(179,222,245)]
#LBLUE = [(209,206,0),(209, 206, 0)]
LBLUE = [(255,191,0 ), (255, 191,0 )]
PINK = [(226,43,138),(226, 43, 138)]
app = application.Application(backend="uia").connect(path=r"C:\Program Files (x86)\Traders Way MetaTrader 4\terminal.exe")
print("started")
from pywinauto.timings import Timings
from pywinauto.timings import wait_until
#app.window(title="Order").print_control_identifiers()
print("getting")
Timings.slow()
x = app.window().children()
WS = ""
for i in x:
#i.texts())
#c = i.children_texts()
#print(c)
#a = ['EURUSD,H4', 'USDCHF,H4', 'GBPUSD,H4', 'USDJPY,H4']
#if all(f in c for f in a):
if 'Workspace' in i.texts():
WS = i
while 1 > 0:
if 1> 0:
for j in WS.children():
#for j in i.children():
print(f"\t{j}")
n = j.texts()[0].split(",")
j.set_focus()
j.maximize()
time.sleep(2)
print(n)
j.capture_as_image().save(f"pair_{n[0]}.png")
img = cv2.imread(f"pair_{n[0]}.png")
img4 = cv2.imread(f"pair_{n[0]}.png")
#mouse.click(button='right', coords=(400,180))
#j.click_input(button="right")
#send_keys('%c')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{RIGHT}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{ENTER}')
#time.sleep(3)
#j.capture_as_image().save(f"pair_2_{n[0]}.png")
#img3 = cv2.imread(f"pair_2_{n[0]}.png")
#img2 = cv2.cvtColor(img3,cv2.COLOR_BGR2HSV)
#img2 = cv2.medianBlur(img2, 5)
#rho = 1 # distance resolution in pixels of the Hough grid
#theta = np.pi / 180 # angular resolution in radians of the Hough grid
#threshold = 200 # minimum number of votes (intersections in Hough grid cell)
#min_line_length = 20 # minimum number of pixels making up a line
#max_line_gap = 20 # maximum gap in pixels between connectable line segments
#lime_mask2 = cv2.inRange(img2, LIME[0], LIME[1])
kernels = np.ones((5, 5), dtype=np.uint8)
#cv2.imwrite("k1.png",lime_mask2)
# Dilating masks to expand boundary.
#lime_mask2 = cv2.dilate(lime_mask2, kernels, iterations=1)
#cv2.imwrite("k2.png", lime_mask2)
# Run Hough on edge detected image
# Output "lines" is an array containing endpoints of detected line segments
#lines = cv2.HoughLines(lime_mask2, rho, theta, threshold)
print("plines")
# for r_theta in lines:
# arr = np.array(r_theta[0], dtype=np.float64)
# r, theta = arr
# # Stores the value of cos(theta) in a
# a = np.cos(theta)
#
# # Stores the value of sin(theta) in b
# b = np.sin(theta)
#
# # x0 stores the value rcos(theta)
# x0 = a * r
#
# # y0 stores the value rsin(theta)
# y0 = b * r
#
# # x1 stores the rounded off value of (rcos(theta)-1000sin(theta))
# x1 = int(x0 + 1000 * (-b))
#
# # y1 stores the rounded off value of (rsin(theta)+1000cos(theta))
# y1 = int(y0 + 1000 * (a))
#
# # x2 stores the rounded off value of (rcos(theta)+1000sin(theta))
# x2 = int(x0 - 1000 * (-b))
#
# # y2 stores the rounded off value of (rsin(theta)-1000cos(theta))
# y2 = int(y0 - 1000 * (a))
#
# # cv2.line draws a line in img from the point(x1,y1) to (x2,y2).
# # (0,0,255) denotes the colour of the line to be
# # drawn. In this case, it is red.
# #cv2.line(img3, (x1, y1), (x2, y2), (0, 0, 255), 2)
#
# # All the changes made in the input image are finally
# written on a new image houghlines.jpg
print("lines")
# for line in np.sort(lines):
# for x1, y1, x2, y2 in line:
# slope = (y2 - y1) / (x2 - x1)
# print(f"{x1},{y1} - {x2},{y2} s:{slope}")
#j.click_input(button="right")
#mouse.click(button='right', coords=(400,180))
#send_keys('%c')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{RIGHT}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{DOWN}')
#send_keys('{ENTER}')
black_mask = cv2.inRange(img, BLACK[0], BLACK[1])
green_mask = cv2.inRange(img, GREEN[0], GREEN[1])
blue_mask = cv2.inRange(img, BLUE[0], BLUE[1])
lime_mask = cv2.inRange(img, LIME[0], LIME[1])
red_mask = cv2.inRange(img, RED[0], RED[1])
white_mask = cv2.inRange(img, WHITE[0], WHITE[1])
tan_mask = cv2.inRange(img, TAN[0], TAN[1])
lblue_mask = cv2.inRange(img, LBLUE[0], LBLUE[1])
pink_mask = cv2.inRange(img, PINK[0], PINK[1])
# Adjust according to your adjacency requirement.
kernel = np.ones((3, 3), dtype=np.uint8)
# Dilating masks to expand boundary.
black_mask = cv2.dilate(black_mask, kernel, iterations=1)
green_mask = cv2.dilate(green_mask, kernel, iterations=1)
blue_mask = cv2.dilate(blue_mask, kernel, iterations=1)
lime_mask = cv2.dilate(lime_mask, kernel, iterations=1)
red_mask = cv2.dilate(red_mask, kernel, iterations=1)
white_mask = cv2.dilate(white_mask, kernel, iterations=1)
tan_mask = cv2.dilate(tan_mask, kernel, iterations=1)
pink_mask = cv2.dilate(pink_mask, kernel, iterations=1)
lblue_mask = cv2.dilate(lblue_mask, kernel, iterations=1)
# Required points now will have both color's mask val as 255.
#black_plus_green = cv2.bitwise_and(green_mask, black_mask)
#blue_plus_green = cv2.bitwise_and(green_mask, blue_mask)
cv2.imwrite(f"pair_{n[0]}_red.png", red_mask)
red_mask = cv2.add(red_mask, white_mask)
cv2.imwrite(f"pair_{n[0]}_combo.png", red_mask)
cv2.imwrite(f"pair_{n[0]}_white.png", white_mask)
cv2.imwrite(f"pair_{n[0]}_blue.png", blue_mask)
cv2.imwrite(f"pair_{n[0]}_green.png", green_mask)
cv2.imwrite(f"pair_{n[0]}_black.png", black_mask)
cv2.imwrite(f"pair_{n[0]}_lime.png", lime_mask)
cv2.imwrite(f"pair_{n[0]}_tan.png", tan_mask)
cv2.imwrite(f"pair_{n[0]}_lblue.png", lblue_mask)
cv2.imwrite(f"pair_{n[0]}_pink.png", pink_mask)
cv2.putText(img4, f"0,0", (0,40), cv2.FONT_HERSHEY_DUPLEX, 1, (30,255,0.0),3)
cv2.putText(img4, f"0,500", (0,500), cv2.FONT_HERSHEY_DUPLEX, 1, (30,255,0.0),3)
cv2.putText(img4, f"500,0", (500,40), cv2.FONT_HERSHEY_DUPLEX, 1, (30,255,0.0),3)
cv2.putText(img4, f"500,500", (500,500), cv2.FONT_HERSHEY_DUPLEX, 1, (30,255,0.0),3)
# Common is binary np.uint8 image, min = 0, max = 255.
# SOME_THRESHOLD can be anything within the above range. (not needed though)
# Extract/Use it in whatever way you want it.
#rgba = cv2.cvtColor(rgb_data, cv2.COLOR_RGB2RGBA)
# Then assign the mask to the last channel of the image
#rgba[:, :, 3] = alpha_data
# Say you want these points in a list form, then you can do this.
start = 10000000
end = 0
blue = ptlist(blue_mask)
tan = ptlist(tank_mask)
lime = ptlist(lime_mask)
lblue = ptlist(lblue_mask)
green = ptlist(green_mask)
black = ptlist(black_mask)
pink = ptlist(pink_mask)
white = ptlist(white_mask)
red = ptlist(red)
print(coord)
if coord[0] in blue:
if coord[1] > blue[coord[0]]["max"]:
blue[coord[0]]["max"] = coord[1]
if coord[1] < blue[coord[0]]["min"]:
blue[coord[0]]["min"] = coord[1]
else:
blue[coord[0]]={"max" : coord[1], "min": coord[1]}
cv2.putText(img4, f"-", (coord[0],coord[1]), cv2.FONT_HERSHEY_PLAIN, .5, (230,155,180.0),3)
cv2.imwrite(f"points_{n[0]}.png", img4)
if pts_list != []:
start = pts_list[0][0];
end = pts_list[-1][0];
for item in pts_list:
if f"r{item[0]}" in blue:
if blue[f"r{item[0]}"]["min"] > item[1]:
blue[f"r{item[0]}"]["min"] = item[1]
if blue[f"r{item[0]}"]["max"] < item[1]:
blue[f"r{item[0]}"]["max"] = item[1]
else:
blue[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(blue)
green = {}
intersection_points = np.where(green_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
if pts_list != []:
if pts_list[0][0] < start:
start= pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in green:
if green[f"r{item[0]}"]["min"] > item[1]:
green[f"r{item[0]}"]["min"] = item[1]
if green[f"r{item[0]}"]["max"] < item[1]:
green[f"r{item[0]}"]["max"] = item[1]
else:
green[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(green)
# intersection_points = np.where(lime_mask> 0)
#print(intersection_points)
# pts_list = [[c, r] for r, c in zip(*intersection_points)]
#print(pts_list)
# lime = {}
#
# if pts_list != []:
# if pts_list[0][0] < start:
# start = pts_list[0][0]
# if pts_list[-1][0] > end:
# end = pts_list[-1][0]
# lime_list = [[c, r] for r, c in zip(*intersection_points)]
#
# end= 0
# for item in pts_list:
# if end == 0:
# end = item[1]
# if f"r{item[0]}" in lime:
# if lime[f"r{item[0]}"]["min"] > item[1]:
# lime[f"r{item[0]}"]["min"] = item[1]
# if lime[f"r{item[0]}"]["max"] < item[1]:
# lime[f"r{item[0]}"]["max"] = item[1]
# else:
# lime[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(lime)
intersection_points = np.where(red_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
red = {}
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in red:
if red[f"r{item[0]}"]["min"] > item[1]:
red[f"r{item[0]}"]["min"] = item[1]
if red[f"r{item[0]}"]["max"] < item[1]:
red[f"r{item[0]}"]["max"] = item[1]
else:
red[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(red)
intersection_points = np.where(white_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
white = {}
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in white:
if white[f"r{item[0]}"]["min"] > item[1]:
white[f"r{item[0]}"]["min"] = item[1]
if white[f"r{item[0]}"]["max"] < item[1]:
white[f"r{item[0]}"]["max"] = item[1]
else:
white[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(white)
intersection_points = np.where(tan_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
tan = {}
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in tan:
if tan[f"r{item[0]}"]["min"] > item[1]:
tan[f"r{item[0]}"]["min"] = item[1]
if tan[f"r{item[0]}"]["max"] < item[1]:
tan[f"r{item[0]}"]["max"] = item[1]
else:
tan[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(tan)
lblue = {}
intersection_points = np.where(lblue_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in lblue:
if lblue[f"r{item[0]}"]["min"] > item[1]:
lblue[f"r{item[0]}"]["min"] = item[1]
if lblue[f"r{item[0]}"]["max"] < item[1]:
lblue[f"r{item[0]}"]["max"] = item[1]
else:
lblue[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(lblue)
intersection_points = np.where(pink_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
pink = {}
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in pink:
if pink[f"r{item[0]}"]["min"] > item[1]:
pink[f"r{item[0]}"]["min"] = item[1]
if pink[f"r{item[0]}"]["max"] < item[1]:
pink[f"r{item[0]}"]["max"] = item[1]
else:
pink[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(pink)
intersection_points = np.where(black_mask> 0)
pts_list = [[c, r] for r, c in zip(*intersection_points)]
black = {}
if pts_list != []:
if pts_list[0][0] < start:
start = pts_list[0][0]
if pts_list[-1][0] > end:
end = pts_list[-1][0]
for item in pts_list:
if f"r{item[0]}" in black:
if black[f"r{item[0]}"]["min"] > item[1]:
black[f"r{item[0]}"]["min"] = item[1]
if black[f"r{item[0]}"]["max"] < item[1]:
black[f"r{item[0]}"]["max"] = item[1]
else:
black[f"r{item[0]}"]={"max": item[1], "min" : item[1]}
#print(black)
lime_list = np.array(lime_list)
lll = np.sort(lime_list)
#print(lime_list)
lime_list = lime_list[lime_list[:,0].argsort()]
#print(lime)
start = lime_list[0][0]
end = lime_list[-1][0]
font = cv2.FONT_HERSHEY_DUPLEX
fontScale =.7
color=(0,65,255)
thickness =1
print(f"start: {start} end:{end}")
cv2.putText(img4, f"[{start:04x},{lime_list[0][1]:04x}]", (lime_list[0][0],lime_list[0][1]), font,
fontScale, color, thickness)
c = 0
for x in range(0,len(lime_list)):
#print(f"{x}: {lime_list[x]} {c} {lime_list[x][0]},{lime_list[x][1]}")
c+=1
if c == 600:
c=0
cv2.putText(img4, f"[{lime_list[x][0]:04x},{lime_list[x][1]:04x}]", (lime_list[x][0], lime_list[x][1]), font,
fontScale, color, thickness)
#cv2.imwrite('points.png', img4)
high = lime_list[0][1]
low = lime_list[0][1]
ptype =""
cmd = ""
prev = np.array([["",""]])
val = "flat"
last = high
for x in range(start,end):
r = f"r{x}"
y = x - 2
z = x - 2
y = f"r{y}"
z = f"r{z}"
#print(f"{x} {r} {start} {end}")
if r not in lime:
p = last
else:
p = lime[r]["max"]
if y not in lime:
pp = p
else:
pp = lime[y]["max"]
#print(f"{p} - {last} {pp} {val} - {r} {lime[r]}")
#print(f"{p[1]} - {end}")
if p > last and p >= pp:
if val != "dn":
print(f"{p} - {last} {val} peak done. going down")
#cv2.putText(img4, f"^", (x, p), cv2.FONT_HERSHEY_T, .5, (255,0.0), 1)
cv2.arrowedLine(img4, (x,p),(x,p-30),(255,0.0), 6,tipLength = 1.5)
ptype = "peak"
val = "dn"
if p < last and p <= pp:
if val != "up":
print(f"{p} - {last} {val} valley done. going up")
#cv2.putText(img4, f"v", (x, p), cv2.FONT_HERSHEY_TRIPLEX, 3, (255,0.0), 4)
cv2.arrowedLine(img4, (x, p), (x, p + 30), (255, 0.0), 6,tipLength = 1.5)
ptype = "valley"
val = "up"
# if p == last:
# val = "flat"
# high = p
# low = p
last = p
r = f"r{x}"
ts = []
for lst in [[blue,"blue"],[black,"black"],[lblue,"lime"],[green,"olive"],[red,"red"],[tan,"wheat"],[pink,"thistle"]]:
if r in lst[0]:
ts.append([lst[0][r]["min"],lst[1]])
if ts == []:
ts = np.array([["",""]])
nl = np.array(sorted(ts, key=lambda k: [k[0],k[1]]))
if ''.join(nl[:,1]) != ''.join(prev[:,1]):
print(f"in {ptype}")
print(' on '.join(nl[:,1]))
prev = nl
if ptype == "peak":
#sell
if "red" in nl and "lime" in nl:
print("SELL")
cv2.putText(img4, f".", (x, 20), cv2.FONT_HERSHEY_PLAIN, .5, (255,255,0), 3)
if cmd != "SELL":
cv2.putText(img4, f"S", (x, 20), cv2.FONT_HERSHEY_PLAIN, 2, (255,255,0), 3)
cmd = "SELL"
#cur.execute(f"insert into chronicle_history (tpair, cmd_date, dictum) values ('{n[0]}',unixepoch(), '{cmd}')")
#cur.execute(f"replace into dictum (tpair, dictum) values ('{n[0]}', '{cmd}')")
else:
#buy
if "olive" in nl and "blue" in nl:
print("BUY")
cv2.putText(img4, f".", (x, 20), cv2.FONT_HERSHEY_PLAIN, .5, (0,255,0.0),3)
elif "lime" not in nl and "thistle" not in nl and "wheat" not in nl and "blue" in nl:
print("BUY")
cv2.putText(img4, f".", (x, 20), cv2.FONT_HERSHEY_PLAIN, .5, (0,255,0.0),3)
if cmd != "BUY":
cv2.putText(img4, f"B", (x, 20), cv2.FONT_HERSHEY_PLAIN, 2, (0,255,0.0), 3)
cmd = "BUY"
#cur.execute(f"insert into chronicle_history (tpair, cmd_date, dictum) values ('{n[0]}',unixepoch(), '{cmd}')")
#cur.execute(f"replace into dictum (tpair, dictum) values ('{n[0]}', '{cmd}')")
cur.execute(f"insert into chronicle_history (tpair, cmd_date, dictum) values ('{n[0]}',unixepoch(), '{cmd}')")
cur.execute(f"replace into dictum (tpair, dictum) values ('{n[0]}', '{cmd}')")
#cv2.imwrite(f"pair_{n[0]}_black_plus_green.png", black_plus_green)
#cv2.imwrite(f"pair_{n[0]}_blue_plus_green.png", blue_plus_green)
cv2.imwrite(f"pair_{n[0]}_blue.png", blue_mask)
cv2.imwrite(f"pair_{n[0]}_green.png", green_mask)
cv2.imwrite(f"pair_{n[0]}_black.png", black_mask)
cv2.imwrite(f"pair_{n[0]}_lime.png", lime_mask)
cv2.imwrite(f"pair_{n[0]}_red.png", red_mask)
cv2.imwrite(f"pair_{n[0]}_white.png", white_mask)
cv2.imwrite(f"pair_{n[0]}_tan.png", tan_mask)
cv2.imwrite(f"pair_{n[0]}_lblue.png", lblue_mask)
cv2.imwrite(f"pair_{n[0]}_pink.png", pink_mask)
cv2.imwrite(f"points_{n[0]}.png", img4)
#exit(1)
#app2 = application.Application(backend="uia").start("python.exe planner.py")
#j.minimize()
#dlg = app.top_window()[0]
#d2 = dlg.child_window(title_re="USDCHF.*", control_type="Pane")
#d2.set_focus()
#print(app.top_window().print_control_identifiers())
#for child in app.top_window().child_window(title="USDJPY,H4", control_type='Dialog'):
#print(child)
#dlg = app.findwindows.find_windows(title=".*" , class_name = "MDIClient")
#print(dlg.print_ctrl_ids())
#dlgs = app.print_ctrl_ids()
#print(dlgs)
#debug_image = dlg.capture_as_image()
#debug_image.save("tst.jpg")
#app_menu = app.top_window().descendants(control_type="MenuBar")[1]
#app_menu.items()[2].select()
#app.top_window().descendants(control_type="MenuItem")[0].click()
#print(app.top_window().descendants(control_type="MenuItem"))