charting refactor into shapes, not debugged

This commit is contained in:
Tim
2024-02-05 20:02:49 -04:00
parent 5587915728
commit 042f96b37c
13 changed files with 614 additions and 114 deletions

View File

@@ -26,7 +26,7 @@ export function subOHLCs( chainId, poolPeriods ) {
socket.emit('subOHLCs', chainId, toSub) socket.emit('subOHLCs', chainId, toSub)
} }
export function unsubPrices( chainId, poolPeriods ) { export function unsubOHLCs( chainId, poolPeriods ) {
const toUnsub = [] const toUnsub = []
for( const [pool,period] of poolPeriods ) { for( const [pool,period] of poolPeriods ) {
const key = `${pool}|${period}` const key = `${pool}|${period}`

View File

@@ -1,5 +1,5 @@
import {uint32max, uint64max} from "@/misc.js"; import {uint32max, uint64max} from "@/misc.js";
import {decodeIEE754, encodeIEE754} from "@/blockchain/common.js"; import {decodeIEE754, encodeIEE754} from "@/common.js";
export const MAX_FRACTION = 65535; export const MAX_FRACTION = 65535;
export const NO_CHAIN = uint64max; export const NO_CHAIN = uint64max;

View File

@@ -1,27 +1,11 @@
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import {prototype} from "@/blockchain/common.js"; import {invokeCallbacks, prototype} from "@/common.js";
export let widget = null export let widget = null
export let chart = null export let chart = null
export let crosshairPoint = null export let crosshairPoint = null
/*
TradingView drawing tool codes:
https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library/#supportedlinetools
text anchored_text note anchored_note signpost double_curve arc icon emoji sticker arrow_up arrow_down arrow_left arrow_right price_label price_note arrow_marker flag vertical_line horizontal_line cross_line horizontal_ray trend_line info_line trend_angle arrow ray extended parallel_channel disjoint_angle flat_bottom anchored_vwap pitchfork schiff_pitchfork_modified schiff_pitchfork balloon comment inside_pitchfork pitchfan gannbox gannbox_square gannbox_fixed gannbox_fan fib_retracement fib_trend_ext fib_speed_resist_fan fib_timezone fib_trend_time fib_circles fib_spiral fib_speed_resist_arcs fib_channel xabcd_pattern cypher_pattern abcd_pattern callout triangle_pattern 3divers_pattern head_and_shoulders fib_wedge elliott_impulse_wave elliott_triangle_wave elliott_triple_combo elliott_correction elliott_double_combo cyclic_lines time_cycles sine_line long_position short_position forecast date_range price_range date_and_price_range bars_pattern ghost_feed projection rectangle rotated_rectangle circle ellipse triangle polyline path curve cursor dot arrow_cursor eraser measure zoom brush highlighter regression_trend fixed_range_volume_profile
*/
export const ShapeType = {
Segment: {name: 'Trend Line', code: 'trend_line'},
Ray: {name: 'Ray', code: 'ray'},
Line: {name: 'Extended Line', code: 'extended'},
HRay: {name: 'Horizontal Ray', code: 'horizontal_ray'},
HLine: {name: 'Horizontal Line', code: 'horizontal_line'},
VLine: {name: 'Vertical Line', code: 'vertical_line'}
}
export function initWidget(el) { export function initWidget(el) {
widget = window.tvWidget = new TradingView.widget({ widget = window.tvWidget = new TradingView.widget({
library_path: "/tradingview/charting_library/", library_path: "/tradingview/charting_library/",
@@ -48,36 +32,41 @@ function initChart() {
chart.crossHairMoved().subscribe(null, (point)=>{ chart.crossHairMoved().subscribe(null, (point)=>{
crosshairPoint=point crosshairPoint=point
const co = useChartOrderStore() const co = useChartOrderStore()
invoke(co.drawingCallbacks, 'onRedraw') invokeCallbacks(co.drawingCallbacks, 'onRedraw')
}) })
} }
// noinspection JSUnusedLocalSymbols // noinspection JSUnusedLocalSymbols
export const ShapeCallback = { export const ShapeCallback = {
// a better word than "draw-er", an ShapeCallback renders one or more shapes in accordance with its onDraw: () => {
// backing builder. for example, a TWAPArtist would manage multiple vertical line shapes, starting }, // start drawing a new shape for the builder
// at the current time and spaced out by the tranche interval. onRedraw: () => {
// use this base class with misc.js/prototype() }, // the mouse moved while in drawing mode
onUndraw: () => {
// }, // drawing was canceled by clicking on a different tool
// ShapeType Events onAddPoint: () => {
// }, // the user clicked a point while drawing (that point is added to the points list)
onDraw: ()=>{}, // start drawing a new shape for the builder onCreate: (shapeId, points, props) => {
onRedraw: ()=>{}, // the mouse moved while in drawing mode }, // the user has finished creating all the control points. drawing mode is exited and the initial shape is created.
onUndraw: ()=>{}, // drawing was canceled by clicking on a different tool onPoints: (shapeId, points) => {
onAddPoint: ()=>{}, // the user clicked a point while drawing (that point is added to the points list) }, // the control points of an existing shape were changed
onCreate: (shapeId, points, props)=>{}, // the user has finished creating all the control points. drawing mode is exited and the initial shape is created. onProps: (shapeId, props) => {
onPoints: (shapeId, points)=>{}, // the control points of an existing shape were changed }, // the display properties of an existing shape were changed
onProps: (shapeId, props)=>{}, // the display properties of an existing shape were changed onMove: (shapeId, points) => {
onMove: (shapeId, points)=>{}, // the entire shape was moved. todo same as onPoints? }, // the entire shape was moved. todo same as onPoints?
onHide: (shapeId, props)=>{}, onHide: (shapeId, props) => {
onShow: (shapeId, props)=>{}, },
onClick: (shapeId)=>{}, // the shape was selected onShow: (shapeId, props) => {
onDeleted: (shapeId)=>{}, },
onClick: (shapeId) => {
}, // the shape was selected
onDelete: (shapeId) => {
},
} }
// noinspection JSUnusedLocalSymbols
export const VerboseCallback = prototype(ShapeCallback, { export const VerboseCallback = prototype(ShapeCallback, {
onDraw: ()=>{console.log('onDraw')}, onDraw: ()=>{console.log('onDraw')},
// onRedraw: ()=>{console.log('onRedraw')}, // onRedraw: ()=>{console.log('onRedraw')},
@@ -111,28 +100,40 @@ export const BuilderUpdateCallback = prototype(ShapeCallback,{
}) })
function invoke(callbacks, prop, ...args) {
if (!callbacks) return
callbacks.forEach((cb)=>{if(prop in cb) cb[prop].call(cb, ...args)})
}
export function drawShape(shapeType, ...callbacks) { export function drawShape(shapeType, ...callbacks) {
// puts the chart into a line-drawing mode for a new shape
console.log('drawShape', callbacks, shapeType.name, shapeType.code) console.log('drawShape', callbacks, shapeType.name, shapeType.code)
const co = useChartOrderStore() const co = useChartOrderStore()
if( co.drawingCallbacks ) if( co.drawingCallbacks )
invoke(co.drawingCallbacks, 'onUndraw') invokeCallbacks(co.drawingCallbacks, 'onUndraw')
co.drawingCallbacks = callbacks co.drawingCallbacks = callbacks
co.drawing = true co.drawing = true
widget.selectLineTool(shapeType.code) widget.selectLineTool(shapeType.code)
invoke(callbacks, 'onDraw') invokeCallbacks(callbacks, 'onDraw')
}
export function createShape(shapeType, points, options, ...callbacks) {
options.shape = shapeType.code
// programatically adds a shape to the chart
let shapeId
if( points.time || points.price )
shapeId = chart.createShape(points, options)
else if( points.length === 1 )
shapeId = chart.createShape(points[0], options)
else
shapeId = chart.createMultipointShape(points, options)
if( callbacks.length )
shapeCallbacks[shapeId] = callbacks
console.log('created shape', shapeId)
return shapeId
} }
export function cancelDrawing() { export function cancelDrawing() {
const co = useChartOrderStore() const co = useChartOrderStore()
if (co.drawing) { if (co.drawing) {
invoke(co.drawingCallbacks, 'onUndraw') invokeCallbacks(co.drawingCallbacks, 'onUndraw')
co.drawing = false co.drawing = false
} }
} }
@@ -151,8 +152,17 @@ export function builderShape(builder, tag, shapeType, ...callbacks) {
export function setPoints( shapeId, points ) { export function setPoints( shapeId, points ) {
if( points.time || points.price )
points = [points]
console.log('setting points', shapeId, points) console.log('setting points', shapeId, points)
widget.activeChart().getShapeById(shapeId).setPoints(points) let shape
try {
shape = chart.getShapeById(shapeId)
}
catch (e) {
return
}
shape.setPoints(points)
} }
@@ -177,27 +187,49 @@ function handleDrawingEvent(id, event) {
co.drawing = false co.drawing = false
const points = shape.getPoints() const points = shape.getPoints()
const props = shape.getProperties() const props = shape.getProperties()
invoke(shapeCallbacks[id], 'onCreate', id, points, props) invokeCallbacks(shapeCallbacks[id], 'onCreate', id, points, props)
invoke(shapeCallbacks[id], 'onPoints', id, points) invokeCallbacks(shapeCallbacks[id], 'onPoints', id, points)
invoke(shapeCallbacks[id], 'onProps', id, props) invokeCallbacks(shapeCallbacks[id], 'onProps', id, props)
} }
} else if (event === 'points_changed') { } else if (event === 'points_changed') {
if (id in shapeCallbacks) { if (id in shapeCallbacks) {
const points = shape.getPoints() const points = shape.getPoints()
console.log('points', points) console.log('points', points)
invoke(shapeCallbacks[id], 'onPoints', id, points) invokeCallbacks(shapeCallbacks[id], 'onPoints', id, points)
} }
} else if (event === 'properties_changed') { } else if (event === 'properties_changed') {
console.log('id in shapes', id in shapeCallbacks, id, shapeCallbacks) console.log('id in shapes', id in shapeCallbacks, id, shapeCallbacks)
if (id in shapeCallbacks) { if (id in shapeCallbacks) {
const props = shape.getProperties() const props = shape.getProperties()
console.log('props', props) console.log('props', props)
invoke(shapeCallbacks[id], 'onProps', id, props) invokeCallbacks(shapeCallbacks[id], 'onProps', id, props)
}
} else if (event === 'move') {
if (id in shapeCallbacks) {
invokeCallbacks(shapeCallbacks[id], 'onMove', id)
} }
} else if (event === 'remove') { } else if (event === 'remove') {
if (id in shapeCallbacks) { if (id in shapeCallbacks) {
invoke(shapeCallbacks[id], 'onDelete', id) invokeCallbacks(shapeCallbacks[id], 'onDelete', id)
}
} else if (event === 'click') {
if (id in shapeCallbacks) {
invokeCallbacks(shapeCallbacks[id], 'onClick', id)
}
} else if (event === 'hide') {
if (id in shapeCallbacks) {
invokeCallbacks(shapeCallbacks[id], 'onHide', id)
}
} else if (event === 'show') {
if (id in shapeCallbacks) {
invokeCallbacks(shapeCallbacks[id], 'onShow', id)
} }
} else } else
console.log('unknown drawing event', event) console.log('unknown drawing event', event)
} }
export function deleteShape(id) {
if( id in shapeCallbacks )
delete shapeCallbacks[id]
chart.removeEntity(id)
}

202
src/charts/shape.js Normal file
View File

@@ -0,0 +1,202 @@
// noinspection JSPotentiallyInvalidUsageOfThis
import {invokeCallback, mixin} from "@/common.js";
import {chart, createShape, deleteShape, drawShape} from "@/charts/chart.js";
import {ref, watch} from "vue";
//
// Usage of Shapes:
// const shape = new Shape(ShapeType.HLine)
// shape.draw()
// shape.points
// > [{time:17228394, price:42638.83}]
//
// shape.model is a vue ref({}) which stores the shape-specific control points, as defined by the shape subclass
// use the shape.model.* fields in components to get reactive effects with the chart.
//
/*
The `name` field must match the user-facing name in the TradingView toolbar UI
TradingView drawing tool codes:
https://www.tradingview.com/charting-library-docs/latest/api/modules/Charting_Library/#supportedlinetools
text anchored_text note anchored_note signpost double_curve arc icon emoji sticker arrow_up arrow_down arrow_left arrow_right price_label price_note arrow_marker flag vertical_line horizontal_line cross_line horizontal_ray trend_line info_line trend_angle arrow ray extended parallel_channel disjoint_angle flat_bottom anchored_vwap pitchfork schiff_pitchfork_modified schiff_pitchfork balloon comment inside_pitchfork pitchfan gannbox gannbox_square gannbox_fixed gannbox_fan fib_retracement fib_trend_ext fib_speed_resist_fan fib_timezone fib_trend_time fib_circles fib_spiral fib_speed_resist_arcs fib_channel xabcd_pattern cypher_pattern abcd_pattern callout triangle_pattern 3divers_pattern head_and_shoulders fib_wedge elliott_impulse_wave elliott_triangle_wave elliott_triple_combo elliott_correction elliott_double_combo cyclic_lines time_cycles sine_line long_position short_position forecast date_range price_range date_and_price_range bars_pattern ghost_feed projection rectangle rotated_rectangle circle ellipse triangle polyline path curve cursor dot arrow_cursor eraser measure zoom brush highlighter regression_trend fixed_range_volume_profile
*/
export const ShapeType = {
Segment: {name: 'Trend Line', code: 'trend_line'},
Ray: {name: 'Ray', code: 'ray'},
Line: {name: 'Extended Line', code: 'extended'},
HRay: {name: 'Horizontal Ray', code: 'horizontal_ray'},
HLine: {name: 'Horizontal Line', code: 'horizontal_line'},
VLine: {name: 'Vertical Line', code: 'vertical_line'},
PriceRange: {name: 'Price Range', code: 'price_range'},
}
class Shape {
constructor(type, model={}) {
// 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 = this.pointsFromModel() // same format as TradingView points for the given shape
this.props = this.propsFromModel() // TradingView shape properties
console.log('points/props', this.points, this.props)
watch(this.model, this.onModelChanged)
if( this.points && this.points.length )
this.create()
}
//
// primary interface methods
//
draw() {
// have the user draw this shape
console.log(`draw ${this.type.name}`)
if (this.id)
throw Error(`Shape already exists ${this.id}`)
drawShape(this.type, new ShapeTVCallbacks(this))
}
create() {
// programatically create the shape using the current this.points
console.log(`create ${this.type.name}`)
if(this.id) {
console.log('warning: re-creating a shape')
this.delete()
}
if(this.points.length === 0)
throw Error('Cannot create a shape with no points')
createShape(this.type, this.points, new ShapeTVCallbacks(this))
}
createOrDraw() {
if(this.id) return
if(this.points && this.points.length)
this.create()
else
this.draw()
}
setPoints(points) {
this.points = points
invokeCallback(this, 'onPoints', points)
this.pointsToModel()
if (points && points.length) {
if (this.id)
chart.getEntity(this.id).setPoints(points)
else
this.create()
}
}
setProps(props) {
this.props = props
invokeCallback(this, 'onProps', props)
this.propsToModel()
if (props && this.id)
chart.getEntity(this.id).setProperties(props)
}
delete() {
if (this.id) {
deleteShape(this.id)
this.id = null
}
else
invokeCallback(this.callbacks, 'onDelete')
}
//
// Model synchronization
//
onModelChanged() {
const points = this.pointsFromModel()
if( points && points !== this.points )
this.setPoints(points)
const props = this.propsFromModel()
if( props && props !== this.props )
this.setProps(props)
}
pointsFromModel() {return null}
pointsToModel() {} // set the model using this.points
propsFromModel() {return null}
propsToModel() {} // set the model using this.props
//
// Overridable shape callbacks
//
onDraw() {} // start drawing a new shape for the builder
onRedraw() {} // the mouse moved while in drawing mode
onUndraw() {} // drawing was canceled by clicking on a different tool
onAddPoint() {} // the user clicked a point while drawing (that point is added to the points list)
onCreate(points, props) {} // the user has finished creating all the control points. drawing mode is exited and the initial shape is created.
onPoints(points) {} // the control points of an existing shape were changed
onProps(props) {} // the display properties of an existing shape were changed
onMove(points) {} // the shape was moved by dragging a drawing element not the control point
onHide(props) {}
onShow(props) {}
onClick() {} // the shape was selected
onDelete() {}
}
class ShapeTVCallbacks {
constructor(shape) {
console.log('shapetvcb', shape)
this.shape = shape
}
onCreate(shapeId, points, props) {
if( this.id )
throw Error(`Created a shape ${shapeId}where one already existed ${this.id}`)
this.id=shapeId
invokeCallback(this.shape, 'onCreate', points, props)
}
onPoints(shapeId, points) {
if( points === this.shape.points ) return // prevent reactive feedback loops
this.shape.setPoints(points)
}
onProps(shapeId, props) {
if( props === this.shape.props ) return // prevent reactive feedback loops
this.shape.setProps(props)
}
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)}
}
export class HLine extends Shape {
constructor(model) {
mixin(model, {price:null,color:null})
super(ShapeType.HLine, model);
}
pointsToModel() {
console.log('pointsToModel', this.points, this.model)
this.model.price = this.points[0].price
}
pointsFromModel() {
console.log('pointsFromModel', this.model.price)
return this.model.price === null ? null : [{time:0,price:this.model.price}]
}
propsToModel() {this.model.color=this.props.linecolor}
propsFromModel() {return this.model.color ? {linecolor: this.model.color} : null}
}

View File

@@ -1,8 +1,9 @@
export function mixin(child, ...parents) { export function mixin(child, ...parents) {
// child is modified directly, assigning fields from parents that are missing in child. parents fields are
// assigned by parents order, highest priority first
for( const parent of parents ) { for( const parent of parents ) {
for ( const key in parent) { for ( const key in parent) {
if (parent.hasOwnProperty(key)) { if (parent.hasOwnProperty(key) && !child.hasOwnProperty(key)) {
child[key] = parent[key]; child[key] = parent[key];
} }
} }
@@ -17,6 +18,15 @@ export function prototype(parent, child) {
return result return result
} }
export function invokeCallback(cbs, prop, ...args) {
if (prop in cbs) cbs[prop].call(cbs, ...args)
}
export function invokeCallbacks(callbacks, prop, ...args) {
if (!callbacks) return
callbacks.forEach((cb)=>invokeCallback(cb, prop, ...args))
}
export function encodeIEE754(value) { export function encodeIEE754(value) {
const buffer = new ArrayBuffer(4); const buffer = new ArrayBuffer(4);

View File

@@ -6,6 +6,7 @@
import {computed} from "vue"; import {computed} from "vue";
import DCABuilder from "@/components/chart/DCABuilder.vue"; import DCABuilder from "@/components/chart/DCABuilder.vue";
import LimitBuilder from "@/components/chart/LimitBuilder.vue"; import LimitBuilder from "@/components/chart/LimitBuilder.vue";
import Test from "@/components/chart/Test.vue";
const props = defineProps(['builder']) const props = defineProps(['builder'])
@@ -16,6 +17,8 @@ const component = computed(()=>{
return DCABuilder return DCABuilder
case 'LimitBuilder': case 'LimitBuilder':
return LimitBuilder return LimitBuilder
case 'Test':
return Test
default: default:
console.error('Unknown builder component '+props.builder.component) console.error('Unknown builder component '+props.builder.component)
return null return null

View File

@@ -6,7 +6,7 @@
import "/tradingview/charting_library/charting_library.js" import "/tradingview/charting_library/charting_library.js"
import "/tradingview/datafeeds/udf/dist/bundle.js" import "/tradingview/datafeeds/udf/dist/bundle.js"
import {onMounted, ref} from "vue"; import {onMounted, ref} from "vue";
import {initWidget} from "@/chart.js"; import {initWidget} from "@/charts/chart.js";
const element = ref() const element = ref()

View File

@@ -4,7 +4,7 @@
<!-- <div v-for="b in co.builderList">{{JSON.stringify(b)}}</div>--> <!-- <div v-for="b in co.builderList">{{JSON.stringify(b)}}</div>-->
<div class="overflow-y-auto"> <div class="overflow-y-auto">
<template v-for="b in co.builderList"> <template v-for="b in co.builderList">
<builder :builder="b"/> <builder-factory :builder="b"/>
</template> </template>
</div> </div>
</div> </div>
@@ -13,7 +13,7 @@
<script setup> <script setup>
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import Toolbar from "@/components/chart/Toolbar.vue"; import Toolbar from "@/components/chart/Toolbar.vue";
import Builder from "@/components/chart/Builder.vue"; import BuilderFactory from "@/components/chart/BuilderFactory.vue";
const co = useChartOrderStore() const co = useChartOrderStore()

View File

@@ -12,8 +12,9 @@
<script setup> <script setup>
import BuilderPanel from "@/components/chart/BuilderPanel.vue"; import BuilderPanel from "@/components/chart/BuilderPanel.vue";
import {ShapeCallback, drawShape, ShapeType, VerboseCallback} from "@/chart.js"; import {drawShape, ShapeCallback, VerboseCallback} from "@/charts/chart.js";
import {prototype} from "@/blockchain/common.js"; import {prototype} from "@/common.js";
import {ShapeType} from "@/charts/shape.js";
const props = defineProps(['builder']) const props = defineProps(['builder'])

View File

@@ -1,20 +1,26 @@
<template> <template>
<!-- todo extract builder-panel --> <!-- :builder="builder" color-tag="limit" --> <!-- todo extract builder-panel --> <!-- :builder="builder" color-tag="limit" -->
<v-card flat rounded="0"> <v-card flat rounded="0">
<v-toolbar dense :color="faintColor"> <v-toolbar dense :color="faintColor" elevation="3">
<span :style="colorStyle" style="width:1em;height:100%">&nbsp;</span> <span :style="colorStyle" style="width:1em;height:100%">&nbsp;</span>
<v-toolbar-title>Limit</v-toolbar-title> <v-toolbar-title>{{ rungs === 1 ? 'Limit' : 'Ladder' }}</v-toolbar-title>
<v-text-field type="number" v-model="price" <!-- <v-text-field type="number" v-model="lower"-->
density="compact" hide-details single-line class="justify-self-start" variant="outlined" <!-- density="compact" hide-details single-line class="justify-self-start" variant="outlined"-->
:color="color" :base-color="color" <!-- :color="color" :base-color="color" min="0"-->
/> <!-- />-->
<!-- <v-text-field type="number" v-model="rungs"-->
<!-- density="compact" hide-details single-line class="justify-self-start" variant="outlined"-->
<!-- :color="color" :base-color="color" min="1"-->
<!-- />-->
{{JSON.stringify(builder)}}
<v-menu> <v-menu>
<template v-slot:activator="{ props }"> <template v-slot:activator="{ props }">
<v-btn variant="plain" v-bind="props" icon="mdi-dots-vertical"/> <v-btn variant="plain" v-bind="props" icon="mdi-dots-vertical"/>
</template> </template>
<v-list> <v-list>
<v-list-subheader :title="'Limit '+ (price?price.toPrecision(5):'')"/> <v-list-subheader :title="'Limit '+ (price?price.toPrecision(5):'')"/>
<v-list-item title="Delete" key="withdraw" value="withdraw" prepend-icon="mdi-delete" color="red" @click="del"/> <v-list-item title="Delete" key="withdraw" value="withdraw" prepend-icon="mdi-delete" color="red"
@click="deleteBuilder"/>
</v-list> </v-list>
</v-menu> </v-menu>
</v-toolbar> </v-toolbar>
@@ -26,60 +32,285 @@
</template> </template>
<script setup> <script setup>
import {computed, ref} from "vue"; import {computed} from "vue";
import {builderShape, chart, setPoints, ShapeType} from "@/chart.js"; import {builderShape, chart, createShape, deleteShape, setPoints} from "@/charts/chart.js";
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import {timestamp} from "@/misc.js";
import Color from "color"; import Color from "color";
import {prototype} from "@/common.js";
import {HLine, ShapeType} from "@/charts/shape.js";
const co = useChartOrderStore() const co = useChartOrderStore()
const props = defineProps(['builder']) const props = defineProps(['builder'])
const shape = new HLine(props.builder)
shape.createOrDraw()
function builderDefaults( builder, defaults ) {
for ( const k in defaults )
if (builder[k] === undefined)
builder[k] = defaults[k] instanceof Function ? defaults[k]() : defaults[k]
}
// Fields must be defined in order to be reactive
builderDefaults(props.builder, {
start: null, // todo
end: null, // todo
lower: null,
upper: null,
rungs: 1,
})
const color = computed(() => { const color = computed(() => {
// todo saturate the color when the corresponding shape is selected https://github.com/Qix-/color // todo saturate the color when the corresponding shape is selected https://github.com/Qix-/color
return props.builder.props.limit?.linecolor return props.builder.color
}) })
const faintColor = computed(() => new Color(color.value).hsl().lightness(97).string()) const faintColor = computed(() => new Color(color.value).hsl().lightness(97).string())
const colorStyle = computed(()=>{return {'background-color':color.value}}) const colorStyle = computed(() => {
return {'background-color': color.value}
})
const price = computed({ //
get() {return props.builder.limit}, // 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()},
})
const end = computed({
get() {return props.builder.end || 0},
set(v) {props.builder.end=v; adjustShapes()},
})
const lower = computed({
get() {
return props.builder.lower
},
set(p) { set(p) {
p = Number(p) p = Number(p)
console.log('set price', p) const hi = props.builder.upper
props.builder.limit = p; if (hi) {
if( drawingShapeId ) { props.builder.upper = Math.max(hi,p)
const shapeId = props.builder.shapes.limit; props.builder.lower = Math.min(hi,p)
console.log('adjust shape', shapeId)
setPoints(shapeId, [{time: timestamp(), price:p}])
} }
else {
props.builder.upper = p
props.builder.lower = p
}
adjustShapes()
} }
}) })
const drawingShapeId = ref(null) 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 del() { function computeRange() {
let range = 0
const series = chart.getSeries()
const bars = series.data().bars();
const final = Math.max(bars.size() - 10, 0)
let count = 0
for (let barIndex = bars.size() - 1; barIndex >= final; barIndex--) {
count++
const [_time, _open, high, low, _close, _volume, _ms] = bars.valueAt(barIndex)
range += (high - low)
}
if (count > 0)
range /= count
else
range = 1
return range
}
const rungs = computed({
get() {
return props.builder.rungs
},
set(r) {
r = Number(r)
props.builder.rungs = r
adjustShapes()
}
})
const prices = computed(()=>{
let lo = props.builder.lower
let hi = props.builder.upper
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)
const result = []
for( let i=0; i<r; i++ )
result.push(lo+i*spacing)
console.log('prices', result)
return result
})
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) {
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) {
//
// 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})
}
}
else {
//
// PRICE RANGE
//
// first set the price range shaded background
const rangePoints = [
{time: start.value, price: props.builder.lower},
{time: end.value, price: props.builder.upper},
];
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
for( let i=0; i<limits.length; i++ ) {
const limit = limits[i]
if (lineShapeIds.length === i) {
// push a new line
const lineId = createShape(ShapeType.HLine, {time:0, price:limit}, {
disableSave: true, disableUndo: true,
overrides: {
lineccolor: props.builder.color,
},
limitLineCallbacks
})
lineShapeIds.push(lineId)
}
else {
// adjust existing line
setPoints(lineShapeIds[i], {time: start.value, price: limit})
}
}
}
}
function deleteShapes() {
if (priceRangeId !== null)
deleteShape(priceRangeId)
for (const id of lineShapeIds)
deleteShape(id)
}
function deleteBuilder() {
co.removeBuilder(props.builder) co.removeBuilder(props.builder)
console.log('remove shape', drawingShapeId.value) deleteShapes()
if( drawingShapeId.value )
chart.removeEntity(drawingShapeId.value)
} }
const callbacks = { function draw() {
onUndraw() {console.log('on undraw')}, builderShape(props.builder, 'limit', ShapeType.HLine, drawLineCallbacks)
onCreate(shapeId, points, props) {drawingShapeId.value = shapeId},
onPoints(shapeId, points) {props.builder.limit = points[0].price; console.log('limit onPoints', points[0].price)},
onDelete(shapeId) {drawingShapeId.value=null; del()},
} }
// if (!props.builder.lower)
if (!props.builder.limit) // draw();
builderShape(props.builder, 'limit', ShapeType.HLine, callbacks)
</script> </script>

View File

@@ -0,0 +1,17 @@
<template>
<v-card flat rounded="0" title="Test">
<v-card-text>
<v-code>
{{JSON.stringify(builder, undefined, 2)}}
</v-code>
</v-card-text>
</v-card>
</template>
<script setup>
const props = defineProps(['builder'])
</script>
<style scoped lang="scss">
</style>

View File

@@ -3,10 +3,10 @@
<span class="arrow align-self-start"><v-icon icon="mdi-arrow-up-bold" color="green"/></span> <span class="arrow align-self-start"><v-icon icon="mdi-arrow-up-bold" color="green"/></span>
<span class="logo">dexorder</span> <span class="logo">dexorder</span>
<v-chip text="ALPHA" size='x-small' color="red" class="align-self-start" variant="text"/> <v-chip text="ALPHA" size='x-small' color="red" class="align-self-start" variant="text"/>
<v-btn variant="flat" prepend-icon="mdi-clock-outline" @click="build('DCABuilder')">DCA</v-btn> <!-- <v-btn variant="flat" prepend-icon="mdi-clock-outline" @click="build('DCABuilder')">DCA</v-btn>-->
<v-btn variant="flat" prepend-icon="mdi-ray-vertex" @click="build('LimitBuilder')">Limit</v-btn> <v-btn variant="flat" prepend-icon="mdi-ray-vertex" @click="build('LimitBuilder')">Limit</v-btn>
<v-btn variant="flat" prepend-icon="mdi-vector-line">Line</v-btn> <!-- <v-btn variant="flat" prepend-icon="mdi-vector-line">Line</v-btn>-->
<v-btn variant="flat" prepend-icon="mdi-question" @click="test">Test</v-btn> <v-btn variant="flat" prepend-icon="mdi-question" @click="build('Test')">Test</v-btn>
<!-- <!--
mdi-ray-start-end mdi-ray-start-end
mdi-vector-polyline mdi-vector-polyline
@@ -18,8 +18,9 @@
<script setup> <script setup>
import {useStore} from "@/store/store.js"; import {useStore} from "@/store/store.js";
import {useChartOrderStore} from "@/orderbuild.js"; import {useChartOrderStore} from "@/orderbuild.js";
import {chart, drawShape, ShapeType} from "@/chart.js"; import {chart, drawShape} from "@/charts/chart.js";
import {timestamp} from "@/misc.js"; import {timestamp} from "@/misc.js";
import {ShapeType} from "@/charts/shape.js";
const s = useStore() const s = useStore()
const co = useChartOrderStore() const co = useChartOrderStore()
@@ -29,10 +30,13 @@ let shape = null
function test() { function test() {
if( shape === null ) const testCb = {
drawShape(ShapeType.VLine, {onCreate:function (shapeId){shape=shapeId}}) onCreate(shapeId) {shape=shapeId},
else }
chart.getShapeById(shape).setPoints([{time:timestamp()}]) if( shape === null ) {
drawShape(ShapeType.HLine, testCb)
}
} }

View File

@@ -1,7 +1,7 @@
import {routeInverted, timestamp} from "@/misc.js"; import {routeInverted, timestamp} from "@/misc.js";
import {MAX_FRACTION, newTranche} from "@/blockchain/orderlib.js"; import {MAX_FRACTION, newTranche} from "@/blockchain/orderlib.js";
import {useOrderStore} from "@/store/store.js"; import {useOrderStore} from "@/store/store.js";
import {encodeIEE754} from "@/blockchain/common.js"; import {encodeIEE754} from "@/common.js";
import {defineStore} from "pinia"; import {defineStore} from "pinia";
import {computed, ref} from "vue"; import {computed, ref} from "vue";
@@ -10,7 +10,7 @@ function unimplemented() { throw Error('Unimplemented') }
// Builders are data objects which store a configuration state // Builders are data objects which store a configuration state
function TrancheBuilder( component, options = {}) { function TrancheBuilder( component, options = {}) {
const id = 'builder-'+Date.now(); const id = crypto.randomUUID()
return {id, component, options, points: {}, shapes: {}, props: {}, build: unimplemented} return {id, component, options, points: {}, shapes: {}, props: {}, build: unimplemented}
} }