First, get bag(s) with sections that have double zippers that can be padlocked together. Then get decent (big) padlocks and a normal flexible bike lock. Put the valuables in the locking section, then put the bike lock through the locked hoop of the padlocks and secure it to something. I've yet to be in a train where there wasn't something you can use for this. You can have a few bike locks that you chain together for more freedom. If there's really nothing then the sheer fact you've gone to the trouble (especially if you've chained several bags together) may put people off -- although it might indicate you've got something valuable to protect.
Keep the keys on you, on a chain round your neck, in a pocket, whatever. You'd probably get away with putting them in some accessible pocket of the bag because what you're trying to do is make your bag look like too much trouble so the thief goes and looks for something easier.
As for people coming in when you're away there's less you can do. If the compartment has doors it's very possible you can lock them from the outside. These rarely use unique keys and are often 'square' or 'triangle' keyhole locks (sorry, can't find a decent image). You can either get the generic keys online or they can generally be locked with the sort of needle-nose pliers you get on decent multi-tools. If there's other people in the room they can get out because there's a normal turnable latch on the inside (of course if they do that they're unlikely to lock it again).
If you can't lock the door you can try to discourage people taking your bed by making it look obviously slept in, consider leaving an old book open on the pillow, or something similar.
If it's shared compartment your best bet is to try and be nice with the others so they'll protect your space. Taking a few nice edibles to share might work past a language barrier, or -- depending on who's there and if you drink -- a drink to share.
Finally, to echo the above, don't advertise that you have valuable stuff. So don't keep your laptop in an Alienware branded laptop bag or your camera in a obvious camera carry. Use generic backpacks and bags -- better if they look beaten up and well traveled. In addition (and slightly competing with) that, it's often better to have a bag that's recognizably yours by color or decoration or whatever. That way you can easily tell if you see someone with it and it minimizes the "Oh, I thought this was mine" defense which will also put people off.
The things you talk of are crimes of opportunity and the perpetrators are looking for the easy target, sadly you just have to make your stuff a more difficult target than the others on the train. It's not foolproof, but it does generally work.