more line manipulation cleanup

This commit is contained in:
Tim
2024-02-06 23:33:51 -04:00
parent a560d47ff6
commit 19a4df2b9b
3 changed files with 249 additions and 212 deletions

View File

@@ -231,5 +231,6 @@ function handleDrawingEvent(id, event) {
export function deleteShape(id) {
if( id in shapeCallbacks )
delete shapeCallbacks[id]
console.log('removing entity', id)
chart.removeEntity(id)
}

View File

@@ -2,7 +2,6 @@
import {invokeCallback} from "@/common.js";
import {chart, createShape, deleteShape, drawShape} from "@/charts/chart.js";
import {watch} from "vue";
//
@@ -35,15 +34,53 @@ export const ShapeType = {
}
function updatePoints(shape, points) {
shape.lock++
try {
chart.getShapeById(shape.id).setPoints(points)
}
finally {
shape.lock--
}
}
function updateProps(shape, props) {
shape.lock++
try {
chart.getShapeById(shape.id).setProps(props)
}
finally {
shape.lock--
}
}
function delShape(shape) {
shape.lock++
try {
deleteShape(shape.id)
} finally {
shape.lock--
}
shape.lock = true
shape.lock = false
}
class Shape {
constructor(type, model={}) {
constructor(type, model={}, onModel=null, onDelete=null) {
// the Shape object manages synchronizing internal data with a corresponding TradingView shape
this.id = null // TradingView shapeId, or null if no TV shape created yet (drawing mode)
this.type = type // ShapeType
this.model = model // subclass-specific
this.points = null // TradingView points for the given shape
this.props = null
watch(this.model, this.onModelChanged.bind(this))
if (onModel !== null)
this.onModel = onModel
if (onDelete !== null )
this.onDelete = onDelete
this.lock = 0 // used to prevent callbacks when we are the ones forcing the chart change
this.create()
}
@@ -81,32 +118,51 @@ class Shape {
this.draw()
}
setModel(model) {
for( const [k,v] of Object.entries(model))
this.model[k] = v
this.setPointsIfDirty(this.pointsFromModel());
this.setPropsIfDirty(this.propsFromModel())
}
setPoints(points) {
invokeCallback(this, 'onPoints', points)
if (points !== null && points.length) {
if (this.id) {
const tvShape = chart.getShapeById(this.id);
setTimeout(()=>tvShape.setPoints(points),0)
updatePoints(this, points)
} else
this.doCreate(points)
}
}
setPointsIfDirty(points) {
if (dirtyPoints(this.points, points))
this.setPoints(points)
}
setProps(props) {
invokeCallback(this, 'onProps', props)
if(this.id) {
console.log(`setting ${this.id} props`, this.props)
setTimeout(()=>chart.getShapeById(this.id).setProperties(props),0)
updateProps(this, props)
}
}
setPropsIfDirty(props) {
if( dirtyProps(this.props, props) )
this.setProps(props)
}
delete() {
if (this.id) {
deleteShape(this.id)
if (this.id!==null) {
delShape(this)
this.id = null
}
else
invokeCallback(this, 'onDelete')
}
@@ -114,20 +170,13 @@ class Shape {
// Model synchronization
//
onModelChanged() {
const points = this.pointsFromModel()
if( points !== null )
this.setPoints(points)
const props = this.propsFromModel()
if( props !== null )
this.setProps(props)
}
pointsFromModel() {return null}
pointsToModel() {} // set the model using this.points
propsFromModel() {return null}
propsToModel() {} // set the model using this.props
onModel(model) {} // called whenever points or props updates the model dictionary
//
// Overridable shape callbacks
@@ -149,12 +198,44 @@ class Shape {
}
function dirtyPoints(pointsA, pointsB) {
if (pointsA === null)
return pointsB !== null
if (pointsB === null)
return true
if (pointsA.length !== pointsB.length)
return true
for (let i = 0; i < pointsA.length; i++) {
const a = pointsA[i];
const b = pointsB[i];
if (a.time !== b.time || a.price !== b.price)
return true
}
return false
}
// B is modifying A
function dirtyProps(propsA, propsB) {
if (propsB===null)
return propsA !== null
const entries = Object.entries(propsB);
if (propsA===null)
return entries.length > 0
for( const [k,v] of entries)
if ( !(k in propsA) || propsA[k] !== v )
return true
return false
}
class ShapeTVCallbacks {
constructor(shape) {
this.shape = shape
}
onCreate(shapeId, points, props) {
if( this.shape.lock ) return
if( this.id )
throw Error(`Created a shape ${shapeId}where one already existed ${this.id}`)
this.shape.id=shapeId
@@ -162,72 +243,91 @@ class ShapeTVCallbacks {
}
onPoints(shapeId, points) {
let dirty = this.shape.points === null || points.length !== this.shape.points.length
for( let i=0; !dirty && i<points.length; i++ ) {
const a = points[i];
const b = this.shape.points[i];
if( a.time !== b.time || a.price !== b.price ) {
dirty = true
break
}
}
if( dirty ) {
if( this.shape.lock ) return
if( dirtyPoints(this.shape.points, points) ) {
this.shape.points = points
this.shape.pointsToModel()
this.shape.onModel(this.shape.model)
}
}
onProps(shapeId, props) {
let dirty = this.shape.props === null
const entries = Object.entries(props)
for( let i=0; !dirty && i<entries.length; i++ ) {
const [k,v] = entries[i]
dirty = !(k in this.shape.props) || this.shape.props[k] !== v
}
if( dirty ) {
if( this.shape.lock ) return
if( dirtyProps(this.shape.props, props) ) {
this.shape.props = props
this.shape.propsToModel()
this.shape.onModel(this.shape.model)
}
}
onDraw() {invokeCallback(this.shape, 'onDraw')}
onRedraw() {invokeCallback(this.shape, 'onRedraw')}
onUndraw() {invokeCallback(this.shape, 'onUndraw')}
onAddPoint() {invokeCallback(this.shape, 'onAddPoint')}
onMove(_shapeId, points) {invokeCallback(this.shape, 'onMove',points)}
onHide(_shapeId, props) {invokeCallback(this.shape, 'onHide',props)}
onShow(_shapeId, props) {invokeCallback(this.shape, 'onShow',props)}
onClick(_shapeId) {invokeCallback(this.shape, 'onClick')}
onDelete(_shapeId, props) {invokeCallback(this.shape, 'onDelete',props)}
onDraw() {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onDraw')
}
onRedraw() {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onRedraw')
}
onUndraw() {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onUndraw')
}
onAddPoint() {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onAddPoint')
}
onMove(_shapeId, points) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onMove',points)
}
onHide(_shapeId, props) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onHide',props)
}
onShow(_shapeId, props) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onShow',props)
}
onClick(_shapeId) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onClick')
}
onDelete(_shapeId, props) {
if( this.shape.lock ) return
invokeCallback(this.shape, 'onDelete',props)
}
}
export class HLine extends Shape {
constructor(model, priceAttr='price', colorAttr='color') {
super(ShapeType.HLine, model);
this.priceAttr = priceAttr
this.colorAttr = colorAttr
constructor(model, onModel=null, onDelete=null) {
super(ShapeType.HLine, model, onModel, onDelete)
}
pointsFromModel() {
if (this.model.price === null) return null
if (this.points.length > 0)
return [{time:this.points[0].time, price:this.model.price}]
return [{time:0, price:this.model.price}]
}
pointsToModel() {
// console.log('pointsToModel', this.points, this.model)
this.model[this.priceAttr] = this.points[0].price
}
pointsFromModel() {
const price = this.model[this.priceAttr];
// console.log('pointsFromModel', price)
return price === null || price === undefined ? null : [{time:price?.time || 0, price:price}]
}
propsToModel() {
console.log('propsToModel', this.props.linecolor)
this.model[this.colorAttr]=this.props.linecolor
console.log('set model from props', this.model)
this.model.price = this.points[0].price
}
propsFromModel() {
console.log('propsFromModel', this.model[this.colorAttr])
const result = this.model[this.colorAttr] ? {linecolor: this.model[this.colorAttr]} : null
console.log('get props from model', this.model[this.colorAttr], result)
return result
return this.model.color ? {linecolor: this.model.color} : null
}
propsToModel() {this.model.color=this.props.linecolor}
}

View File

@@ -4,7 +4,7 @@
<v-toolbar dense :color="faintColor" elevation="3">
<span :style="colorStyle" style="width:1em;height:100%">&nbsp;</span>
<v-toolbar-title>{{ rungs === 1 ? 'Limit' : 'Ladder' }}</v-toolbar-title>
<v-text-field type="number" v-model="lower"
<v-text-field type="number" v-model="lineAPrice"
density="compact" hide-details single-line class="justify-self-start" variant="outlined"
:color="color" :base-color="color" min="0"
/>
@@ -17,7 +17,7 @@
<v-btn variant="plain" v-bind="props" icon="mdi-dots-vertical"/>
</template>
<v-list>
<v-list-subheader :title="'Limit '+ (lower?lower.toPrecision(5):'')"/>
<v-list-subheader :title="'Limit '+ (lineAPrice?lineAPrice.toPrecision(5):'')"/>
<v-list-item title="Delete" key="withdraw" value="withdraw" prepend-icon="mdi-delete" color="red"
@click="deleteBuilder"/>
</v-list>
@@ -32,19 +32,47 @@
<script setup>
import {computed} from "vue";
import {builderShape, chart, createShape, deleteShape, setPoints} from "@/charts/chart.js";
import {chart} from "@/charts/chart.js";
import {useChartOrderStore} from "@/orderbuild.js";
import Color from "color";
import {prototype} from "@/common.js";
import {HLine, ShapeType} from "@/charts/shape.js";
const co = useChartOrderStore()
const props = defineProps(['builder'])
const shape = new HLine(props.builder, 'lower', 'color')
shape.onDelete = deleteBuilder
shape.createOrDraw()
// we keep two special control lines as the edge of the ranges and then deletable lines in-between
const lineAPrice = computed({
get() { return props.builder.priceA },
set(v) { props.builder.priceA = v===null ? v : Number(v)
adjustShapes()
}})
const lineA = new HLine(
{price:null,color:null},
(line)=>{props.builder.priceA = line.price; props.builder.color = line.color},
deleteBuilder
)
const lineBPrice = computed({
get() { return props.builder.priceB },
set(v) { props.builder.priceB = v===null ? v : Number(v)
adjustShapes()
}})
const lineB = new HLine(
{price:null,color:null},
(line)=>{props.builder.priceB = line.price;props.builder.color = line.color},
deleteBuilder
)
let interiorLines = []
function createInteriorLine(price) {
const line = new HLine({price:price}) // todo
interiorLines.push(line)
line.create()
}
function builderDefaults( builder, defaults ) {
@@ -58,8 +86,8 @@ function builderDefaults( builder, defaults ) {
builderDefaults(props.builder, {
start: null, // todo
end: null, // todo
lower: null,
upper: null,
priceA: null,
priceB: null,
rungs: 1,
color: null,
})
@@ -75,11 +103,6 @@ const colorStyle = computed(() => {
})
//
// Builder parameters: lower, upper, rungs
// lower/upper is the price range and rungs >= 1 is the number of lines split into that range
//
const start = computed({
get() {return props.builder.start || 0},
set(v) {props.builder.start=v; adjustShapes()},
@@ -90,47 +113,6 @@ const end = computed({
set(v) {props.builder.end=v; adjustShapes()},
})
const lower = computed({
get() {
return props.builder.lower
},
set(p) {
p = Number(p)
const hi = props.builder.upper
if (hi) {
props.builder.upper = Math.max(hi,p)
props.builder.lower = Math.min(hi,p)
}
else {
props.builder.upper = p
props.builder.lower = p
}
adjustShapes()
}
})
const upper = computed({
get() {
return props.builder.upper
},
set(p) {
p = Number(p)
const lo = props.builder.lower
if (lo) {
console.log('max', lo, p, Math.max(lo,p))
props.builder.upper = Math.max(lo,p)
props.builder.lower = Math.min(lo,p)
}
else {
props.builder.upper = p
props.builder.lower = p
}
adjustShapes()
}
})
function computeRange() {
let range = 0
const series = chart.getSeries()
@@ -162,16 +144,15 @@ const rungs = computed({
const prices = computed(()=>{
let lo = props.builder.lower
let hi = props.builder.upper
let a = props.builder.priceA
let b = props.builder.priceB
const r = props.builder.rungs
if ( !lo || !r ) return [] // no data
if (r===1) return [(hi+lo)/2] // single line
const spacing = (hi-lo)/(r-1)
console.log('price spacing', spacing, hi, lo, r)
if ( a===null || !r ) return [] // no data
if (r===1) return [a] // single line
const spacing = (b-a)/(r-1)
const result = []
for( let i=0; i<r; i++ )
result.push(lo+i*spacing)
result.push(a+i*spacing)
console.log('prices', result)
return result
})
@@ -181,70 +162,24 @@ let lineShapeIds = []
let priceRangeId = null
const limitLineCallbacks = {
onCreate(shapeId, points, properties) {
lineShapeIds.push(shapeId)
},
onPoints(shapeId, points) {
console.log('limit onPoints', shapeId, points[0].price, lineShapeIds)
if (lineShapeIds.length === 0) return
const r = rungs.value;
if (r === 1 && lineShapeIds[0] === shapeId ) {
const range = computeRange()
props.builder.lower = points[0].price - range/2
props.builder.upper = points[0].price + range/2
}
else if ( lineShapeIds[0] === shapeId ) {
console.log('setting lower')
props.builder.lower = points[0].price
}
else if ( lineShapeIds[lineShapeIds.length-1] === shapeId ) {
console.log('setting upper')
props.builder.upper = points[0].price
}
},
onMove(shapeId, points) {
console.log('limit onMove')
},
onProps(shapeId, properties) {
console.log('limit onProps', properties, properties.linecolor)
// props.builder.color = properties.linecolor
},
onDelete(shapeId) {
deleteBuilder()
},
}
const drawLineCallbacks = prototype(limitLineCallbacks, {
})
function adjustShapes() {
return
const limits = prices.value
console.log('adjust shapes', limits)
if (limits.length === 1) {
if( limits.length === 0 ) {
lineA.delete()
lineB.delete()
for( const line of interiorLines )
line.delete()
interiorLines = []
}
else if (limits.length === 1) {
//
// SINGLE LINE
//
if (lineShapeIds.length > 1) {
deleteShapes()
}
// remove range shape
if (priceRangeId) {
chart.removeEntity(priceRangeId)
priceRangeId = null
}
if (lineShapeIds.length === 0) {
// create a line
const lineId = createShape(ShapeType.HLine, {time:0, price: props.builder.lower}, {}, limitLineCallbacks)
lineShapeIds.push(lineId)
} else {
// adjust the line
console.log('adjusting line', lineShapeIds[0])
setPoints(lineShapeIds[0], {time:0, price: props.builder.lower})
}
lineA.setModel({price:limits[0]})
lineB.delete()
for( const line of interiorLines )
line.delete()
interiorLines = []
}
else {
//
@@ -252,25 +187,26 @@ function adjustShapes() {
//
// first set the price range shaded background
const rangePoints = [
{time: start.value, price: props.builder.lower},
{time: end.value, price: props.builder.upper},
{time: start.value, price: lineAPrice.value},
{time: end.value, price: lineBPrice.value},
];
if (priceRangeId !== null)
setPoints(priceRangeId, rangePoints)
else {
priceRangeId = createShape(ShapeType.PriceRange, rangePoints, {
disableSave: true, disableSelection: true, disableUndo: true, lock: true,
// https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Shapes-and-Overrides
overrides: {
fillLabelBackground: false,
lineccolor: props.builder.color,
backgroundColor: faintColor.value,
},
})
}
while( lineShapeIds.length > limits.length )
lineShapeIds.pop()
// now adjust the lines
// todo price range shape
// if (priceRangeId !== null)
// setPoints(priceRangeId, rangePoints)
// else {
// priceRangeId = createShape(ShapeType.PriceRange, rangePoints, {
// disableSave: true, disableSelection: true, disableUndo: true, lock: true,
// // https://www.tradingview.com/charting-library-docs/latest/customization/overrides/Shapes-and-Overrides
// overrides: {
// fillLabelBackground: false,
// lineccolor: props.builder.color,
// backgroundColor: faintColor.value,
// },
// })
// }
while( interiorLines.length > Math.max(0,limits.length-2) )
interiorLines.pop()
// now adjust the interior lines
for( let i=0; i<limits.length; i++ ) {
const limit = limits[i]
if (lineShapeIds.length === i) {
@@ -298,7 +234,11 @@ function deleteShapes() {
// deleteShape(priceRangeId)
// for (const id of lineShapeIds)
// deleteShape(id)
shape.delete()
lineA.delete()
lineB.delete()
for (const line of interiorLines)
line.delete()
interiorLines = []
}
@@ -308,12 +248,8 @@ function deleteBuilder() {
}
function draw() {
builderShape(props.builder, 'limit', ShapeType.HLine, drawLineCallbacks)
}
// if (!props.builder.lower)
// draw();
if (!props.builder.priceA)
lineA.createOrDraw();
</script>